1 year, 10 months ago.

Divide integer into bytes

How would I divide an integer into bytes and keep the leading zeros?

1 Answer

1 year, 10 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.