c++typeconvertervaluestack

How to Set upper and lower bytes of an short int in C++


I got to ask How to Set upper and lower bytes of an (short int) in C++ .

we use this for get upper and lower but now how to set upper and lower bytes of a short int.

int number = 3510;

char upper = number >> 8;

char lower = number && 8;

thanks :)

after reading your answer i found a problem look my code please :

int number = 55;
int mynumber = 0;

char upper = number >> 8;

char lower = number && 8;

mynumber = (mynumber & 0xff00) | lower;
mynumber = (mynumber & 0x00ff) | (upper << 8);

printf("%i",mynumber);

it just return 1 but must return 55 ! how to fix it?


Solution

  • To set upper byte:

    number = (number & 0x00ff) | (upper << 8);
    

    To set lower byte:

    number = (number & 0xff00) | lower;
    

    Both upper and lower should be char or unsigned char type.