user98651 user98651 - 1 year ago 160
C++ Question

Copying a 16 bit integer to a two byte array

I am wondering why when I copy a 16 bit number to a two byte array, it results in only copying to the first index of the array.
My code is as follows:

#include <iostream>
#include <stdint.h>
#include <stdio.h>
#include <cstring>

using namespace std;

int main(){
uint16_t my_num = 1; // This should be 0000000000000001, right?
unsigned char my_arr[2]; // This should hold 16 bits, right?

memcpy(my_arr, &my_num, sizeof(my_num)); // This should make my_arr = {00000000, 00000001}, right?

printf("%x ", my_arr[0]);
printf("%x ", my_arr[1]);
cout << endl;
// "1 0" is printed out

return 0;

Thanks in advance.

Answer Source

This is because of endianness of your platform. The bytes of multi-byte uint16_t are stored in the address space lowest-byte-first. You can see what's going on by trying the same program with a number that is larger than 256:

uint16_t my_num = 0xABCD;

The result will have 0xCD in the first byte and 0xAB in the second byte.

You can force a specific endianness by using functions from hton/ntoh family.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download