Skip to main content
gamedev.net
🔒 Locked

code snippet question

Started by mjs1 Nov 21, 2004 at 9:34 PM 2 replies 900+ views
Original Post
mjs1
mjs1
I have a code snippet that looks like this: char inChar; unsigned short rShort; inFile.get(inChar); rShort = inChar; // first byte is little one inFile.get(inChar); rShort |= ((unsigned short)inChar << 8); I'm unclear what the last line does. The goal of the code snippet is to build an unsigned short out of two chars read from a file stream. I haven't seen the "<<" operator used outside of cin and cout much. What exactly is the last line of code doing? Thanks!
Aldenar
Aldenar
When used with integers, the "<<" operator is a left shift. In that example, it means that inChar will be shifted 8 bits to the left. Basicly, say inChar = 90 = 0x5a:

inChar = 0101 1010

inChar << 8 = 0101 1010 0000 0000 = 0x5a00 = 23040

It is another way of multiplying, left-shifting a number by n bits is like multiplying it by 2^n.

There is also the ">>" operator that is a right shift (can be seen as a divide by 2^n).

In your example, inChar is 8 bits, rShort is 16 bits, it means that the first value that is read from the file will be stored in the lower 8 bits of rShort, and the second value will be stored in the upper 8 bits of rShort.
etothex
etothex
shifting all of the bits in inChar left by 8. Simply put, multiplying by 2^8 = 256.

EDIT: Beat to it by a better description.
mjs1
mjs1
Thanks very much!!

Makes sense now.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.