How to make 1 byte from 8 bit samples in java or c?
I have 8 bit samples with random values (called headers) and I have commands with hexadecimal values, see bellow:
[8 bit][command]
\ |
\ \------------------ [01 30 00 00 = hex start the mac开发者_如何学编程hine]
\
+-------------------+
| 00001111 = hi |
| 00000000 = hello |
| 00000101 = wassup |
+-------------------+
How do you translate the 8 bit samples to 1 byte and join it with the above hex value ?
In both languages, you can use bitwise operations.
So in C, if you have:
uint32_t command;
uint8_t sample;
You can concatenate these into e.g. a 64-bit data type as follows:
uint64_t output = (uint64_t)command << 32
| (uint64_t)sample;
If you instead want an array of output bytes (for serializing over RS-232 or whatever), then you can do something like:
uint8_t output[5];
output[0] = sample;
output[1] = (uint8_t)(command >> 0);
output[2] = (uint8_t)(command >> 8);
output[3] = (uint8_t)(command >> 16);
output[4] = (uint8_t)(command >> 32);
精彩评论