SRA
SRA

Reputation: 1691

what does this mean in c# while converting to a unsigned int 32

(uint)Convert.ToInt32(elements[0]) << 24;

Upvotes: 3

Views: 261

Answers (3)

apoorv020
apoorv020

Reputation: 5670

As Mongus Pong said, shifts are usually used to multiply and divide very fast. (And can cause weird problems due to overflow).

I'm going to go out on a limb and trying to guess what your code is doing.

If elements[0] is a byte element(that is to say, it contains only 8 bits), then this code will result in straight-forward multiplication by 2^24. Otherwise, it will drop the 24 high-order bits and multiply by 2^24.

Upvotes: 0

Mongus Pong
Mongus Pong

Reputation: 11477

The << is the left shift operator.

Given that the number is a binary number, it will shift all the bits the specified amount to the left.

If we have

2 << 1

This will take the number 2 in binary (00000010) and shift it to the left one bit. This gives you 4 (000000100).

Overflows

Note that once you get to the very left, the bits are discarded. So assuming you are working with an 8 bit sized integer (I know c# uint like you have in your example is 32 bits - I dont want to have to type out a 32 bit digit, so just assume we are on 8 bits)

255 << 1

will return 254 (11111110).

Use

Being very careful of the overflows mentioned before, bit shifting is a very fast way to multiply or divide by 2. In a highly optimised environment (such as games) this is a very useful way to perform arithmetic very fast.

However, in your example, it is taking only the right most 8 bits of the number making them the left most 8 bits (multiplying it by 16,777,216) . Why you would want do this, I could only guess.

Upvotes: 4

Giorgi
Giorgi

Reputation: 30883

I guess you are referring to Shift operators.

Upvotes: 1

Related Questions