Reputation: 670
I am trying to read data stored in a byte array as per seem API documentation for a project I am working on. I am used to dealing with byte arrays but I'm not sure how to view or Mae sense of the bits within a byte.
This image is from a page in the documentation
It states that the "IIN" value is 24 bits long starting at byte number 2 bit number 7 and finishing at byte number 4 and bit 0. How can I select this data and store it in a variable? Is the following extension method achievable?
public static int GetSubBitsValue(this byte[] all, int startbyte, int startbit, int endbyte, int endbit)
{
//magic here
}
Upvotes: 0
Views: 63
Reputation: 52280
A byte contains 8 bits. Bits are numbered by their power of two, so they go from 7 to 0 from most significant bit to least significant. Thus:
byte myByte = SomeFunctionToGetAByte();
bool isBit7Set = myByte & (2 ^ 7);
bool isBit6Set = myByte & (2 ^ 6);
bool isBit5Set = myByte & (2 ^ 5);
bool isBit4Set = myByte & (2 ^ 4);
bool isBit3Set = myByte & (2 ^ 3);
bool isBit2Set = myByte & (2 ^ 2);
bool isBit1Set = myByte & (2 ^ 1);
bool isBit0Set = myByte & (2 ^ 0);
Since this value starts on bit 7 and ends on bit 0, it happens to fall on byte boundaries, so it ought to be pretty easy to get.
Since it is 24 bits long you will need to read 3 bytes (24 bits ÷ 8 bits per byte = 3 bytes). But you need to know what order the bytes come in-- most significant digits first, which is how you'd write it by hand, and is common on a Mac/68000 architecture; or least least significant digits first, which is common on Wintel architectures. The documentation has to tell you this.
Let's assume you have the full array of bytes in an array.
byte[] bytes = GetByteArray();
You need to grab all three bytes, shift one of them left 8 bits (or multiply it by 2^8 or 256), shift another left 16 bits (multiply it by 2^16 or 65536), then add all three up (or OR them, which will have the same result).
If the format is Big Endian (MSB first) the value will be
int value = bytes[2] << 16 | bytes[3] << 8 | bytes[4];
If it's little-endian (LSB first) then it is:
int value = bytes[4] << 16 | bytes[3] << 8 | bytes[2];
Upvotes: 1
Reputation: 5506
I would use the following once you have selected your byte:
bool myBit = (inputByte & (2 ^ 7)) == (2 ^ 7);
Upvotes: 0