I'm making a function that will allow the user to pass a double value, and then return a UInt16.
This is my code:
public static UInt16 Value_To_BatteryVoltage(double value)
{
var ret = ((int)value << 8);
var retMod = (value % (int)value) * 10;
return (UInt16)(ret + retMod);
}
Basically what it does is as follows, function call:
Value_To_BatteryVoltage(25.10)
Will return: 6401
I can check the result by doing:
public static double VoltageLevel(UInt16 value)
{
return ((value & 0xFF00) >> 8) + ((value & 0x00FF) / 10.0);
}
This is working as expected, BUT, if I do:
Value_To_BatteryVoltage(25.11) //notice the 0.11
I get the wrong result, because:
public static UInt16 Value_To_BatteryVoltage(double value)
{
var ret = ((int)value << 8); // returns 6400 OK
var retMod = (value % (int)value) * 10; //returns 0.11 x 10 = 1.1 WRONG!
return (UInt16)(ret + retMod); //returns 6400, because (UInt16)(6400 + 1.1) = 6401 same as 25.10 so I've lost precision
}
So the question is, is there some way to do this kind of conversion without losing precision?
If I understand the question, you want to store the Characteristic (interger-part) in the first 8 bits of UInt16. And the Mantissa (fractional-part) in the second 8 bits.
This is one way to do it. I treat the double like a string and split it at the decimal. For example:
public static UInt16 Value_To_BatteryVoltage(double value)
{
string[] number = value.ToString().Split('.');
UInt16 c = (UInt16)(UInt16.Parse(number[0]) << 8);
UInt16 m = UInt16.Parse(number[1]);
return (UInt16)(c + m);
}
And here is the output:
Related
I have a Byte scaleValue with the value 3 (0000.0011 binary)
Now I want to set the BIT 3 and 4 (Scale) of the Byte Config (see image) with help of my Byte scaleValue but it does not work.
Before: 0000.0000 (if configByte has the init value 0)
After: 0001.1000
Here is my code:
configByte = (byte) (configByte | (scaleValue << 3));
Byte Config:
If configByte is the entire 8-bit chunk, and scaleValue is the value (currently in bits 0/1) that you want to inject into bits 3/4, then fundamentally you need:
configByte = (byte)(configByte | (scaleValue << 3));
However, this assumes that:
bits 3/4 in configByte are currently zero
only bits 0/1 in scaleValue are set (or not)
If those two assumptions aren't true, then you need to mask out the issue with ... masks:
configByte = (byte)((configByte & 231) | ((scaleValue & 3) << 3));
The & 231 removes bits 3/4 in the old value. The & 3 enforces just bits 0/1 in the new value (before the shift)
You can use these extension methods:
public static bool GetBit(this byte data, byte position)
{
byte mask = (byte)(1 << position);
return (data & mask) != 0;
}
public static byte SetBit(this byte data, byte position, bool value)
{
byte mask = (byte)(1 << position);
if (value)
{
return (byte)(data | mask);
}
else
{
return (byte)( data & (~mask));
}
}
static void Main(string[] args)
{
byte data = 0b0000100;
if (data.GetBit(2))
{
}
data = data.SetBit(4, true);
data = data.SetBit(2, false);
}
I am trying to program a PLC address generator. However there I need to make bit wise addition to find the next available address.
Meaning if I start with the adress 0.0 and add 2 bit then the next free adress would be 0.3. It goes up until 0.7 then then next adress is 1.0 up to 1.7 then 2.0 and so on.
Depending on what datatype I add to the addition the next free adress should be calculated.
For example a bool is one bit. 0.1 -> 0.2 -> 0.3 and so on
A Byte has 8 bits if I add a byte and the last free adress was 0.4 the next free address should be 2.0.
A Word has 16 Bits so 0.0 -> 2.0 -> 4.0 and so on.
A Double Word has 32 Bits so 0.0 -> 4.0 -> 8.0 and so on.
I am looking for an implementation in c# where I can add the different types as input and it adds it and gives me corresponding address and stores then next free address internal for the next operation.
For example:
Type Startaddress
1 Bool 0.0 (->0.1)
2 Bool 0.1 (->0.2)
3 Byte 1.0 (->1.7) as 8 bits are required
4 Bool 2.0 (->2.1)
5 Word 3.0 (->4.7) as 16 bits are required
6 Double Word 5.0 (->8.7) as 32 bits are required
Any idea how I could implement that apart from a lot of if else and loop? I am looking for an elegant overloaded operator approach.
The only "trick" to your problem is the notation of .0-.7 for bit addresses and the C# types don't match up exactly with the types in your specification.
The main class I show here stores the address as bit offset internally, and provides the integer and decimal fraction through the fAddress() method.
Your example shows alignment on byte boundaries, but doesn't align words or double words--so that's what I implemented. Comments show how to do that differently if the PLC cares.
You'll need to add the code to store values at the byte.bit type addresses.
using System;
namespace PLCAddress
{
class Program
{
static void Main(string[] args)
{
PLCAddress a = new PLCAddress();
float address;
bool boolA = true;
byte byteA = 7;
ushort wordA = 65535;
uint dblwordA = 4294967295;
address = a.Store(boolA);
Console.WriteLine(address.ToString());
address = a.Store(boolA);
Console.WriteLine(address.ToString());
address = a.Store(byteA);
Console.WriteLine(address.ToString());
address = a.Store(boolA);
Console.WriteLine(address.ToString());
address = a.Store(wordA);
Console.WriteLine(address.ToString());
address = a.Store(dblwordA);
Console.WriteLine(address.ToString());
}
}
public class PLCAddress
{
protected uint _address;
public PLCAddress()
{
_address = 0;
}
public float Store(bool b)
{
float rv = fAddress();
_address += 1;
return rv;
}
public float Store(byte b)
{
float rv = fAddress(8);
_address += 8;
return rv;
}
public float Store(ushort b)
{
float rv = fAddress(8); // use fAddress(16) if words need to be on word boundaries
_address += 16;
return rv;
}
public float Store(uint b)
{
float rv = fAddress(8); // use fAddress(32) if double words need to be on double word boundaries
_address += 32;
return rv;
}
protected float fAddress()
{
return (float)Whole + (float)Fraction / 10;
}
protected float fAddress(uint alignment)
{
uint roundup = alignment - 1;
uint mask = ~roundup;
uint AlignedAddress = _address + roundup;
AlignedAddress = AlignedAddress & mask;
_address = AlignedAddress;
return fAddress();
}
protected uint Whole
{
get { return _address / 8; }
}
protected uint Fraction
{
get { return _address % 8; }
}
}
}
You can store these addresses in an int - the lower part in the first 3 bits, the rest in the rest of the bits and get the address from there. This allows you to do normal arithmetic on these addresses and numbers. If the address is in a string you can do something like this:
public static int ToIntAddress(this string str)
{
var values = str.Split('.');
int lower = int.Parse(values[1]);
int higher = int.Parse(values[0]) << 3;
return lower + higher;
}
public static string ToAddress(this int address) => $"{address >> 3}.{address & 0b0111}";
("3.0".ToIntAddress() + 15).ToAddress() // "4.7"
("5.0".ToIntAddress() + 31).ToAddress() // "8.7"
("0.4".ToIntAddress() + 7).ToAddress() // "1.3"
I personally prefer an object oriented approach:
public class MemoryManager
{
private int _dataSize = 0;
public enum DataTypes
{
Bool = 1,
Byte = 8,
Word = 16,
DWord = 32
}
public MemoryLocation Add(DataTypes type)
{
var address = GetCurrentAddress();
_dataSize += (int)type;
return address;
}
private MemoryLocation GetCurrentAddress()
{
int currentByteLocation = _dataSize / 8;
int currentBitLocation = _dataSize % 8;
return new MemoryLocation(currentByteLocation, currentBitLocation);
}
}
public class MemoryLocation
{
public MemoryLocation(int byteLocation, int bitIndex)
{
ByteLocation = byteLocation;
BitIndex = bitIndex;
}
public int ByteLocation { get; private set; }
public int BitIndex { get; private set; }
public override string ToString()
{
return string.Format("[{0},{1}]", ByteLocation, BitIndex);
}
}
I whipped this out real quick but you can use other more streamlined methods to generate the next address.
You can use this:
public int BitWiseAdd()
{
int FirstNumber = 50;
int SecondNumber = 60;
while (SecondNumber !=0)
{
int carry = FirstNumber & SecondNumber;
FirstNumber = FirstNumber ^ SecondNumber;
SecondNumber = carry << 1;
}
return FirstNumber;
}
I'm making a tile based 2d platformer and every byte of memory is precious. I have one byte field that can hold values from 0 to 255, but what I need is two properties with values 0~15. How can I turn one byte field into two properties like that?
do you mean just use the lower 4 bits for one value and the upper 4 bits for the other?
to get two values from 1 byte use...
a = byte & 15;
b = byte / 16;
setting is just the reverse as
byte = a | b * 16;
Using the shift operator is better but the compiler optimizers usually do this for you nowadays.
byte = a | (b << 4);
To piggy back off of sradforth's answer, and to answer your question about properties:
private byte _myByte;
public byte LowerHalf
{
get
{
return (byte)(_myByte & 15);
}
set
{
_myByte = (byte)(value | UpperHalf * 16);
}
}
public byte UpperHalf
{
get
{
return (byte)(_myByte / 16);
}
set
{
_myByte = (byte)(LowerHalf | value * 16);
}
}
Below are some properties and some backing store, I've tried to write them in a way that makes the logic easy to follow.
private byte HiAndLo = 0;
private const byte LoMask = 15; // 00001111
private const byte HiMask = 240; // 11110000
public byte Lo
{
get
{
// ----&&&&
return (byte)(this.hiAndLo & LoMask);
}
set
{
if (value > LoMask) //
{
// Values over 15 are too high.
throw new OverflowException();
}
// &&&&0000
// 0000----
// ||||||||
this.hiAndLo = (byte)((this.hiAndLo & HiMask) | value);
}
}
public byte Hi
{
get
{
// &&&&XXXX >> 0000&&&&
return (byte)((this.hiAndLo & HiMask) >> 4);
}
set
{
if (value > LoMask)
{
// Values over 15 are too high.
throw new OverflowException();
}
// -------- << ----0000
// XXXX&&&&
// ||||||||
this.hiAndLo = (byte)((hiAndLo & LoMask) | (value << 4 ));
}
}
I am trying to process a WM_MOUSEMOVE message in C#.
What is the proper way to get an X and Y coordinate from lParam which is a type of IntPtr?
Try:
(note that this was the initial version, read below for the final version)
IntPtr xy = value;
int x = unchecked((short)xy);
int y = unchecked((short)((uint)xy >> 16));
The unchecked normally isn't necessary (because the "default" c# projects are unchecked)
Consider that these are the definitions of the used macros:
#define LOWORD(l) ((WORD)(((DWORD_PTR)(l)) & 0xffff))
#define HIWORD(l) ((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff))
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
Where WORD == ushort, DWORD == uint. I'm cutting some ushort->short conversions.
Addendum:
one and half year later, and having experienced the "vagaries" of 64 bits .NET, I concur with Celess (but note that 99% of the Windows messages are still 32 bits for reasons of compatibility, so I don't think the problem isn't really big now. It's more for the future and because if you want to do something, you should do it correctly.)
The only thing I would make different is this:
IntPtr xy = value;
int x = unchecked((short)(long)xy);
int y = unchecked((short)((long)xy >> 16));
instead of doing the check "is the IntPtr 4 or 8 bytes long", I take the worst case (8 bytes long) and cast xy to a long. With a little luck the double cast (to long and then to short/to uint) will be optimized by the compiler (in the end, the explicit conversion to int of IntPtr is a red herring... If you use it you are putting yourself at risk in the future. You should always use the long conversion and then use it directly/re-cast it to what you need, showing to the future programmers that you knew what you were doing.
A test example: http://ideone.com/a4oGW2 (sadly only 32 bits, but if you have a 64 bits machine you can test the same code)
Correct for both 32 and 64-bit:
Point GetPoint(IntPtr _xy)
{
uint xy = unchecked(IntPtr.Size == 8 ? (uint)_xy.ToInt64() : (uint)_xy.ToInt32());
int x = unchecked((short)xy);
int y = unchecked((short)(xy >> 16));
return new Point(x, y);
}
- or -
int GetIntUnchecked(IntPtr value)
{
return IntPtr.Size == 8 ? unchecked((int)value.ToInt64()) : value.ToInt32();
}
int Low16(IntPtr value)
{
return unchecked((short)GetIntUnchecked(value));
}
int High16(IntPtr value)
{
return unchecked((short)(((uint)GetIntUnchecked(value)) >> 16));
}
These also work:
int Low16(IntPtr value)
{
return unchecked((short)(uint)value); // classic unchecked cast to uint
}
int High16(IntPtr value)
{
return unchecked((short)((uint)value >> 16));
}
- or -
int Low16(IntPtr value)
{
return unchecked((short)(long)value); // presumption about internals
} // is what framework lib uses
int High16(IntPtr value)
{
return unchecked((short)((long)value >> 16));
}
Going the other way
public static IntPtr GetLParam(Point point)
{
return (IntPtr)((point.Y << 16) | (point.X & 0xffff));
} // mask ~= unchecked((int)(short)x)
- or -
public static IntPtr MakeLParam(int low, int high)
{
return (IntPtr)((high << 16) | (low & 0xffff));
} // (IntPtr)x is same as 'new IntPtr(x)'
The accepted answer is good translation of the C definition. If were dealing with just the raw 'void*' directly, then would be mostly ok. However when using 'IntPtr' in a .Net 64-bit execution environment, 'unchecked' will not stop conversion overflow exceptions from being thrown from inside IntPtr. The unchecked block does not affect conversions that happen inside IntPtr funcitons and operators. Currently the accepted answer states that use of 'unchecked' is not necesary. However the use of 'unchecked' is absolutely necessary, as would always be the case in casting to negative values from a larger type.
On 64-bit, from the accepted answer:
var xy = new IntPtr(0x0FFFFFFFFFFFFFFF);
int x = unchecked((short)xy); // <-- throws
int y = unchecked((short)((uint)xy >> 16)); // gets lucky, 'uint' implicit 'long'
y = unchecked((short)((int)xy >> 16)); // <-- throws
xy = new IntPtr(0x00000000FFFF0000); // 0, -1
x = unchecked((short)xy); // <-- throws
y = unchecked((short)((uint)xy >> 16)); // still lucky
y = (short)((uint)xy >> 16); // <-- throws (short), no longer lucky
On 64-bit, using extrapolated version of DmitryG's:
var ptr = new IntPtr(0x0FFFFFFFFFFFFFFF);
var xy = IntPtr.Size == 8 ? (int)ptr.ToInt64() : ptr.ToInt32(); // <-- throws (int)
int x = unchecked((short)xy); // fine, if gets this far
int y = unchecked((short)((uint)xy >> 16)); // fine, if gets this far
y = unchecked((short)(xy >> 16)); // also fine, if gets this far
ptr = new IntPtr(0x00000000FFFF0000); // 0, -1
xy = IntPtr.Size == 8 ? (int)ptr.ToInt64() : ptr.ToInt32(); // <-- throws (int)
On performance
return IntPtr.Size == 8 ? unchecked((int)value.ToInt64()) : value.ToInt32();
The IntPtr.Size property returns a constant as compile time literal that is capable if being inlined across assemblies. Thus is possible for the JIT to have nearly all of this optimized out. Could also do:
return unchecked((int)value.ToInt64());
- or -
return unchecked((int)(long)value);
- or -
return unchecked((uint)value); // traditional
and all 3 of these will always call the equivalient of IntPtr.ToInt64(). ToInt64(), and 'operator long', are also capable of being inlined, but less likely to be. Is much more code in 32-bit version than the Size constant. I would submit that the solution at the top is maybe more symantically correct. Its also important to be aware of sign-extension artifacts, which would fill all 64-bits reguardless on something like (long)int_val, though i've pretty much glossed over that here, however may additionally affect inlining on 32-bit.
Useage
if (Low16(wParam) == NativeMethods.WM_CREATE)) { }
var x = Low16(lParam);
var point = GetPoint(lParam);
A 'safe' IntPtr mockup shown below for future traverlers.
Run this without setting the WIN32 define on 32-bit to get a solid simulation of the 64-bit IntPtr behavour.
public struct IntPtrMock
{
#if WIN32
int m_value;
#else
long m_value;
#endif
int IntPtr_ToInt32() {
#if WIN32
return (int)m_value;
#else
long l = m_value;
return checked((int)l);
#endif
}
public static explicit operator int(IntPtrMock value) { //(short) resolves here
#if WIN32
return (int)value.m_value;
#else
long l = value.m_value;
return checked((int)l); // throws here if any high 32 bits
#endif // check forces sign stay signed
}
public static explicit operator long(IntPtrMock value) { //(uint) resolves here
#if WIN32
return (long)(int)value.m_value;
#else
return (long)value.m_value;
#endif
}
public int ToInt32() {
#if WIN32
return (int)value.m_value;
#else
long l = m_value;
return checked((int)l); // throws here if any high 32 bits
#endif // check forces sign stay signed
}
public long ToInt64() {
#if WIN32
return (long)(int)m_value;
#else
return (long)m_value;
#endif
}
public IntPtrMock(long value) {
#if WIN32
m_value = checked((int)value);
#else
m_value = value;
#endif
}
}
public static IntPtr MAKELPARAM(int low, int high)
{
return (IntPtr)((high << 16) | (low & 0xffff));
}
public Main()
{
var xy = new IntPtrMock(0x0FFFFFFFFFFFFFFF); // simulate 64-bit, overflow smaller
int x = unchecked((short)xy); // <-- throws
int y = unchecked((short)((uint)xy >> 16)); // got lucky, 'uint' implicit 'long'
y = unchecked((short)((int)xy >> 16)); // <-- throws
int xy2 = IntPtr.Size == 8 ? (int)xy.ToInt64() : xy.ToInt32(); // <-- throws
int xy3 = unchecked(IntPtr.Size == 8 ? (int)xy.ToInt64() : xy.ToInt32()); //ok
// proper 32-bit lParam, overflow signed
var xy4 = new IntPtrMock(0x00000000FFFFFFFF); // x = -1, y = -1
int x2 = unchecked((short)xy4); // <-- throws
int xy5 = IntPtr.Size == 8 ? (int)xy4.ToInt64() : xy4.ToInt32(); // <-- throws
var xy6 = new IntPtrMock(0x00000000FFFF0000); // x = 0, y = -1
int x3 = unchecked((short)xy6); // <-- throws
int xy7 = IntPtr.Size == 8 ? (int)xy6.ToInt64() : xy6.ToInt32(); // <-- throws
var xy8 = MAKELPARAM(-1, -1); // WinForms macro
int x4 = unchecked((short)xy8); // <-- throws
int xy9 = IntPtr.Size == 8 ? (int)xy8.ToInt64() : xy8.ToInt32(); // <-- throws
}
Usualy, for low-level mouse processing I have used the following helper (it also considers that IntPtr size depends on x86/x64):
//...
Point point = WinAPIHelper.GetPoint(msg.LParam);
//...
static class WinAPIHelper {
public static Point GetPoint(IntPtr lParam) {
return new Point(GetInt(lParam));
}
public static MouseButtons GetButtons(IntPtr wParam) {
MouseButtons buttons = MouseButtons.None;
int btns = GetInt(wParam);
if((btns & MK_LBUTTON) != 0) buttons |= MouseButtons.Left;
if((btns & MK_RBUTTON) != 0) buttons |= MouseButtons.Right;
return buttons;
}
static int GetInt(IntPtr ptr) {
return IntPtr.Size == 8 ? unchecked((int)ptr.ToInt64()) : ptr.ToInt32();
}
const int MK_LBUTTON = 1;
const int MK_RBUTTON = 2;
}
Scenario:
I have a string of hexadecimal characters which encode 8-bit signed integers. Each two characters represent a byte which employ the leftmost (MSB) bit as the sign (rather than two's complement). I am converting these to signed ints within a loop and wondered if there's a better way to do it. There are too many conversions and I am sure there's a more efficient method that I am missing.
Current Code:
string strData = "FFC000407F"; // example input data, encodes: -127, -64, 0, 64, 127
int v;
for (int x = 0; x < strData.Length/2; x++)
{
v = HexToInt(strData.Substring(x * 2, 2));
Console.WriteLine(v); // do stuff with v
}
private int HexToInt(string _hexData)
{
string strBinary = Convert.ToString(Convert.ToInt32(_hexData, 16), 2).PadLeft(_hexData.Length * 4, '0');
int i = Convert.ToInt32(strBinary.Substring(1, 7), 2);
i = (strBinary.Substring(0, 1) == "0" ? i : -i);
return i;
}
Question:
Is there a more streamlined and direct approach to reading two hex characters and converting them to an int when they represent a signed int (-127 to 127) using the leftmost bit as the sign?
Just covert it to an int and handle the sign bit by testing the size of the converted number and masking off the sign bit.
private int HexToInt(string _hexData)
{
int number = Convert.ToInt32(_hexData, 16);
if (number >= 0x80)
return -(number & 0x7F);
return number;
}
Like this: (Tested)
(int)unchecked((sbyte)Convert.ToByte("FF", 16))
Explanation:
The unchecked cast to sbyte will perform a direct cast to a signed byte, interpreting the final bit as a sign bit.
However, it has a different range, so it won't help you.
sbyte SignAndMagnitudeToTwosComplement(byte b)
{
var isNegative = ((b & 0x80) >> 7);
return (sbyte)((b ^ 0x7F * isNegative) + isNegative);
}
Then:
sbyte ReadSignAndMagnitudeByte(string hex)
{
return SignAndMagnitudeToTwosComplement(Convert.ToByte(hex,16));
}