• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

C/C++, << and | in variable definitions?

Deathheadmoth

Limp Gawd
Joined
Aug 23, 2001
Messages
288
Hi, I have a question about something I've never seen used before in C or C++..

If you do this:
int test = (3<<2);
And then cout test, you get 12.

What does that mean? I've never seen << used in defining a variable.

Also, if you do this:
int test = (3<<2) | (5<<1);
You get 15.

Again, I'm not following what's happening. What is | doing?

The reason I'm asking is because I saw someone try to define an IP address as this:
long IP = ((155<<24)|(246<<16)|(14<<8)|11);

I know an IP address is 32 bits, so it seems like its storing the 155 in the first 8 bits, 246 in the second, and so on.. but how does this actually work? What do the operators mean?

I tried googling this stuff, but it's not a very easy thing to google

Thanks in advance for your help.
 
<< is the binary left-shift operator.

X << Y left-shifts X by Y places in binary.

3 (decimal) = 11 (binary)
if we shif it to the left twice, we get
1100 (binary) = 12 (decimal)
 
I is inclusive-or.

(3<<2) = 1100 (binary)

(5<<1) = 1010 (binary)

1100 | 1010 = 1110 (binary)

1110 = 14 (I'm assuming you meant 14 and not 15.)
 
lshift by x (number << x) is the same as multiplying by 2^x and is usually faster than doing a multiply or divide.
 
If you were to store an IP address this way, what would be the best way to extract the IP address from the long?
 
long ip;

// ip is a.b.c.d

int a = (ip >> 24) & 255;
int b = (ip >> 16) & 255;
int c = (ip >> 8) & 255;
int d = (ip) & 255;
 
Deathheadmoth said:
If you were to store an IP address this way, what would be the best way to extract the IP address from the long?

Doing shifts is neat, but it can be slow.

Code:
long ip;

// ip is a.b.c.d

int a = (ip >> 24) & 255;
int b = (ip >> 16) & 255;
int c = (ip >> 8) & 255;
int d = (ip) & 255;

// most platforms use four bytes for "int", so you're wasting a lot of space for
// your expanded storage. Doing the shifts is pretty slow.

// if you know the endianness of your platform, you can easily make an array;

unsigned char* p = &ip;

// now, you don't have to do any shifting, and you can find the components
// in an interesting way. These offsets are for little-endian machines (like x86)

// p[0] is the same as d
// p[1] is the same as c
// p[2] is the same as b
// p[3] is the same as a
 
Back
Top