I have 2 bytes
that should populate this way:
first number (4b) second number (12b)
So 4 bit can be between 1-15 And 12 bit can be between 1-50
So i have this Bytes Array
:
byte[] packetArrayBytes = new byte[Length];
I have 2 bytes
that should populate this way:
first number (4b) second number (12b)
So 4 bit can be between 1-15 And 12 bit can be between 1-50
So i have this Bytes Array
:
byte[] packetArrayBytes = new byte[Length];
The way I've understood the question is that you've got these two (presumably) unsigned integers a
and b
:
(I'll be writing them in hexadecimal to make it easier to read)
a: 0x0000000X
b: 0x00000XXX
Where a
is the 4-bit number and b
is the 12-bit one, with the X
s marking the bits containing the relevant values.
You want to store them in two separate 8-bit chunks: c: 0x00
and d: 0x00
So you need to shift the bits into position, like this:
byte[] packetArrayBytes = new byte[2];
uint intA = 0xF; // Allowed range is 0-15 (0x0-0xF)
uint intB = 0xABC; // Allowed range is 0-4095 (0x0-0xFFF)
// Need to convert from uint to bytes:
byte[] bytesA = BitConverter.GetBytes(intA);
byte[] bytesB = BitConverter.GetBytes(intB);
byte a = bytesA[0]; // a is 0x0F
byte b = bytesB[1]; // b is 0x0A
int c = 0x00; // c is 0x00
int d = bytesB[0]; // d is 0xBC
// Mask out 4 least significant bits of a,
// then shift 4 bits left to place them in the most significant bits (of the byte),
// then OR them into c.
c |= (a & 0x0F) << 4; // c is now 0xF0
// Mask out 4 least significant bits of b,
// then OR them into c.
c |= b & 0x0F; // c is now 0xFA
packetArrayBytes[0] = (Byte)c;
packetArrayBytes[1] = (Byte)d;
Console.WriteLine(BitConverter.ToString(packetArrayBytes)); // Prints "FA-BC"
After doing these operations, the values of a
and b
should be placed in the bytes c
and d
like this:
c: 0xFA
d: 0xBC
. Which you can then place into your array.
To get the values back you just do these same operations in reverse.
If a
and b
are signed values, I believe the same operations work, but you'll have to make sure you're not interpreting them as unsigned when reading the data back into numbers.