Hello,
i have a problem and i do not understand why this happen.
I want to write a function where i can extract X-Bits from a Byte Array of 8 Bytes.
What i need are i.e. 12 Bit, started from Byte 0 Bit 4 to Byte 1 Bit 7.
This may differ, that's why i want to have this function which i just call and say start-bit and length.
This is what i have:
The result of the function is Hex: 412
But i expect 341.
I also played around with byteswap, endians and so on, but i could not find the right way.
Can someone help me to find a solution what the problem is?
It must be something with the memory storage of the bytes, that this is swapped.
But how is it swapped and what should i do? If the memory / processor is using the bytes in a different way, do i have to bring the byte array in a form that the processor is using it like i want and then swap it back?
Thanks a lot.
Thomas
i have a problem and i do not understand why this happen.
I want to write a function where i can extract X-Bits from a Byte Array of 8 Bytes.
What i need are i.e. 12 Bit, started from Byte 0 Bit 4 to Byte 1 Bit 7.
This may differ, that's why i want to have this function which i just call and say start-bit and length.
This is what i have:
Code:
unsigned char byte1[8] = { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xFF };
unsigned long result = 0;
unsigned long realResult = 0;
unsigned long ByteToLong( byte const *pData, byte BitOffset, byte BitSize)
{
unsigned long bytetolongvalue = 0;
byte c = ( BitOffset + BitSize ) / 8;
c * 8 == BitOffset + BitSize ? 0 : c++;
memcpy ( &bytetolongvalue, pData, c );
bytetolongvalue <<= ( sizeof ( bytetolongvalue ) - c ) * 8 + BitOffset;
bytetolongvalue >>= 8 * sizeof ( bytetolongvalue ) - BitSize;
return bytetolongvalue;
}
void setup()
{
Serial.begin(9600);
Serial.println("--12 Bit 4...16--");
result = ByteToLong(byte1, 4, 12);
Serial.print("Byte To Long result: ");
Serial.println(result, HEX);
// CORRECT RESULT IS:
realResult = ((byte1[1] & 0xFF) << 4);
realResult |= (((byte1[0]) >> 4) & 0x0F);
Serial.print("realResult: ");
Serial.println(realResult ,HEX);
}
void loop()
{
}
The result of the function is Hex: 412
But i expect 341.
I also played around with byteswap, endians and so on, but i could not find the right way.
Can someone help me to find a solution what the problem is?
It must be something with the memory storage of the bytes, that this is swapped.
But how is it swapped and what should i do? If the memory / processor is using the bytes in a different way, do i have to bring the byte array in a form that the processor is using it like i want and then swap it back?
Thanks a lot.
Thomas