Dany
Dany

Reputation: 2174

Get a integer value from HEX data

I have Hex data as

Byte[] data = new Byte[2];
data[0]=FF;
data[1]=FF;

Here the binary representation of this data is as

1111 1111 1111 1111

Here i want to find the integer value from bit 0 to 11 only. (From left to right) But i am not getting how to find value with minimal complexity? Please help me.Thanks in advance.

Upvotes: 0

Views: 377

Answers (4)

AGo
AGo

Reputation: 304

short value = 0xFFFF;
value = value & 0x0FFF; 

This operation turns four higher bits to 0. You can tur your char val[1] = val[1] & 0x0F

Upvotes: 1

DThought
DThought

Reputation: 1314

This is basic stuff...

you don't have "hex" data, but 2 byte sized integers.

in pseudocode ( i don't speak c# fluently) :

int value=data[1]<<8 | data[0];
int maskedvalue=value & 4095; // bits 0..11 inclusive set

now maskedvalue holds the value with only the lower 11 bits set.

Upvotes: 0

opewix
opewix

Reputation: 5083

Converting byte array to string:

StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
       sb.AppendFormat("{0:x2}", b)
}
return sb.ToString();

then, parsing string to int

 int a = int.Parse("10026AB0", NumberStyles.AllowHexSpecifier);

Upvotes: 0

If you want only specific bits, you can apply a logical AND with a bit mask.
In your case the bit mask is 0000 1111 1111 1111 (bits zero to and including eleven) or 0FFF.

You mention "from left to right", so maybe instead you want 1111 1111 1111 0000 (FFF0) - bits 4 up to and including 15.

Upvotes: 2

Related Questions