Challenge: Set Integer Bytes

Test your knowledge by solving this coding challenge.

The reverseBytes function

The input is an unsigned integer, and you must reverse the order of its bytes.

To understand this, let’s assume the input is in hex. The beauty of the hexadecimal system is that we can view the bytes individually as opposed to the decimal system.

For example, if we take the number 3735928559, we can’t know the value of each of the 4 bytes just by looking at the number. We could convert it into binary, but this still requires one extra operation, and binary is a bit hard to read.

Let’s use base 16 or hex. Its value is DEADBEEF or 0xDEADBEEF, which you can obtain with a calculator. The 0x is a prefix to signify that the number is in hex. It isn’t part of the actual number.

The beauty of hex is that each digit or letter represents 4 bits, so two digits or letters together occupy 8 bits or 1 byte. To clarify, in 0xDEADBEEF:

  • The first byte is DE
  • The second byte is AD
  • The third byte is BE
  • The fourth byte is EF

If we convert the number in binary, split the bits into bytes, and then convert each byte to decimal, we’d get the same value as if we convert the above hex bytes in decimal.

Input and output

Input: x = 0xDEADBEEF;
Output: x = 0xEFBEADDE;

The bytes of the input are DE, AD, BE, and EF. If we reverse the bytes, we get EF, BE, AD, DE, or 0xEFBEADDE.

We can use printf to print numbers in hex if we use the %x specifier instead of %d or %u.

Coding challenge

Complete the reverseBytes function. It will receive a pointer to an unsigned int. You should modify the unsigned integer in place.

Get hands-on with 1200+ tech skills courses.