zylski
zylski

Reputation: 31

Convert 11 bit hex value to a signed 32 bit int

I am given a 11 bit signed hex value that must be stored in an int32 data type. When I cast the hex value to an int 32, the 11 bit hex value is obviously smaller then the int32 so it 0 fills the higher order bits.

Basically i need to be able to store 11 bit signed values in an int32 or 16 from a given 11 bit hex value.

For example. String hex = 0x7FF;

If i cast this to int32 using Int.parse(hex, System.Globalization.Numbers.Hexvalue); I get 2047 when it should be -1 (according to the 11 bit binary 111 1111)

How can I accomplish this in c#?

Upvotes: 0

Views: 1624

Answers (2)

L.B
L.B

Reputation: 116138

string hex = "0x7FF";
var i = (Convert.ToInt32(hex, 16) << 21) >> 21;

Upvotes: 1

user555045
user555045

Reputation: 64904

It's actually very simple, just two shifts. Shifting right keeps the sign, so that's useful. In order to use it, the sign of the 11 bit thing has to be aligned with the sign of the int:

x <<= -11;

Then do the right shift:

x >>= -11;

That's all.

The -11, which may seem odd, is just a shorter way to write 32 - 11. That's not in general the same thing, but shift counts are masked by 31 (ints) or 63 (longs), so in this case you can use that shortcut.

Upvotes: 1

Related Questions