Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
5 years, 11 months ago.
Divide integer into bytes
How would I divide an integer into bytes and keep the leading zeros?
1 Answer
5 years, 11 months ago.
An integer variable or a text string containing an integer?
If it's a variable then
int valueToConvert; char bytes[sizeof(int)]; for (int i=0;i<sizeof(int);i++) { bytes[i] = *(((char *)&valueToConvert) + i); }
It it's a string then I'm not sure what you mean by keeping the leading zeros. You can convert the string to an integer and then count the number of leading zeros by looking at the string length or number of '0' characters before the first non-zero but that doesn't directly convert into bytes in any meaningful way.
This
https://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work
and that
https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit
will help you... And also check sprintf printf etc...
posted by Kamil M 17 Jan 2019