I don’t come from a low-level development background, so I’m not sure how to convert the below instruction to an integer…
Basically I have a microprocessor which tells me which IO’s are active or inactive. I send the device an ASCII command and it replies with a WORD about which of the 15 I/O’s are open/closed… here’s the instruction:
- Unit Answers “A0001/” for only DIn0 on, “A????/” for All Inputs Active
- Awxyz/ – w=High Nibble of MSB in 0 to ? ASCII Character 0001=1, 1111=?, z=Low Nibble of LSB.
At the end of the day I just want to be able to convert it back into a number which will tell me which of the 15 (or 16?) inputs are active.
I have something hooked up to the 15th I/O port, and the reply I get is “A8000”, if that helps?
Can someone clear this up for me please?
You can use the BitConverter class to convert an array of bytes to the integer format you need.
If you’re getting 16 bits, convert them to a UInt16.
C# does not define the endianness. That is determined by the hardware you are running on. Intel and AMD processors are little-endian. You can learn the endian-ness of your platform using BitConverter.IsLittleEndian. If the computer running .NET and the hardware providing the data do not have the same endian-ness, you would have to swap the two bytes.
If the bits are hardware flags, it is plausible that all 16 are used to mean something. When bits are used to represent a signed number, one of the bits is used to represent positive vs. negative. Since the hardware is providing status bits, none of the bits should be interpreted as a sign.
If you want to know if a specific bit is active, you can use a bit mask along with the
&operator. For example, the binary maskcorresponds to the hex number
To learn if the third bit from the right is toggled on, use
UPDATE
If the manufacturer says the value 8000 (I assume hex) represents Channel 15 being active, look at it like this:
Your bit mask
Based in that info from the manufacturer, the left-most bit corresponds to Channel 15.
You can use that mask like: