简体   繁体   中英

(C) Bit shifting/char placement in a short int variable

New to C.

The overall goal here is to put a character in a short int, and have it occupy the left byte of the short int rather than the right byte. To elaborate -

I'm trying to take a variable:

unsigned short int packager;

(short int is 2 bytes.)


and put this char in it:

unsigned char temp = A;

(A in binary is 01000001.)


So, how is this done? What I want the short int to look like is this:

0100 0001 0000 0000


My current idea is to work in hex values. If I could say something like packager = 0x(temp) or 0x(temp) and append a 0? (idk..) and then use shifting or masking.. I might be able to get somewhere. The biggest roadblock seems to be my inability to use a variable to make a hex value. Again, the overall goal is to put a character in a short int, and have it occupy the left byte of the short int rather than the right byte.

Just use

packager = A << 8

Note that speaking of left and right bytes is a bad habit. Instead use high and low. Left and right may be interpreted by some as dependent on address order and hence endianess (unless you really want something to do with address ordering).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM