Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 633
user98651 Avatar asked Mar 10 '23 16:03

user98651


1 Answers

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.

like image 82
Sergey Kalinichenko Avatar answered Apr 07 '23 10:04

Sergey Kalinichenko