0

I'm using AES to encrypt some data that I'm going to send in a packet. I need to store an integer in an array of 8 bit elements. To make this clear, my array is declared as:

uint8_t in[16] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
                  0x00,0x00,0x00,0x00};

I need to be able to store an integer in this array and then easily retrieve the data in the receiving client. Is there an easy way to accomplish this?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user1754045
  • 175
  • 1
  • 6
  • 15

1 Answers1

1

This is usually achieved via bit-shifting:

int i = 42;
in[0] = i & 0xff;
in[1] = (i >> 8)  & 0xff;
in[2] = (i >> 16) & 0xff;
in[3] = (i >> 24) & 0xff;

Note that you cannot always be guaranteed that an int is four bytes. However, it's easy enough to turn the above code into a loop, based on sizeof i.

Retrieving the integer works as follows:

int i = in[0] | (in[1] << 8) | (in[2] << 16) | (in[3] << 24);

Of course, if you are about to encrypt this with AES, you need to give some thought to a sensible padding algorithm. Currently you look like you're heading towards zero-padding, which is far from optimal.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254