1

the question is how to get bytes numbers from an integer without "0"? I mean when I want to:

printf("%x", 67305985);

the output is: 04030201. Is there any opportunity to get 4321(without "0") in the output? I tried to convert an integer to unsigned char array, but there were the same problem.

Thanks for your time.

1 Answers1

0

One way to do this is to use a combination of bit-shifts, and bit masking.

If you & a 32-bit integer against the 32-bit integer 0x000000FFu the result is an integer where only the bits that were A: already set and B: located in the last 8 bits of the number are set. To select other parts of the integer, you can bitshift by a multiple of 8. I.E. (x >> 8) &0x000000FFuto select the second byte from the right,(x >> 16) & 0x000000FFu to select the third.

You could then print out each of these as regular unsigned integers in decimal format.

I'm not sure how the performance of this method would compare to casting an unsigned integer pointer to an unsigned char pointer and doing it that way.

Trevor Galivan
  • 373
  • 2
  • 13
  • Also, if you do this I would highly reccomend defining 0x000000FFu in a macro so that you don't have to copy paste it over an over again yourself. (This might also make the code slightly easier to read if you give a descriptive name to the macro) – Trevor Galivan May 24 '20 at 19:22