Copying a 16-bit integer to a double-byte array

I am wondering why, when I copy a 16-bit number to a double-byte array, it only results in 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 0000 0000 0000 0001, 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.

+4
source share
1 answer

This is due to the endianness of your platform. Bytes of several bytes uint16_tare stored in the address space with a minimum byte. You can see what happens by trying the same program with a number that is more than 256:

uint16_t my_num = 0xABCD;

The result will be 0xCDin the first byte and 0xABin the second byte.

, hton/ntoh family.

+7

Source: https://habr.com/ru/post/1660778/


All Articles