I need to repackage data to be sent in 7 bit words with the MSB padded. I have tried different approaches but the last byte comes out wrong. The 16 bit value 0x87E5 would be encoded into three bytes like this:
original.
10000111 11100101
encoded.
01000011 01111001 00100000
I have been trying to do it like this but the third byte comes out wrong. This is what I have tried so far, there might be better / more clever way of achiving the same thing though. Interested to hear your input on this.
// 1.) ........10000111 11100101 00000000
// 2.) ...>> 01000011 11110010 10000000
// 3.) .................>> 01111001 01000000
// 4.) ...............................>> 00100000
Code:
unsigned char byte[4] = {0};
int large = 0x87E5; // 10000111 11100101 00000000 00000000
large >>= 1; // 01000011 11110010 10000000 00000000
printf("%x\n", large);
large = htons(large);
memcpy(&byte, &large, 3);
binary(byte[0]); // 01000011 >OK
byte[1] >>= 1;
binary(byte[1]); // 01111001 >OK
large >>= 1;
memcpy(&byte[2], &large, 3);
byte[4] >>= 1;
binary(byte[4]); // 01111111 >wrong! should be 00100000?
BTW, the call to the binary() function prints in binary to stdout, thanks Dino for the hint on how to do this.