Newbie256
Newbie256

Reputation:

first 16 bit of a 32 bit hex

Please excuse my lack of knowledge here but could someone let me know how i can get the first 16 bits of a 32 bit hex number.

Upvotes: 0

Views: 2755

Answers (5)

Guffa
Guffa

Reputation: 700432

This will get you the 32 bit number as a four byte array:

Dim bytes As Byte() = BitConverter.GetBytes(number)

To get the first two bytes as a signed 16 bit number:

Dim first As Int16 = BitConverter.ToInt16(bytes, 0)

To get the first two bytes as an unsigned 16 bit number:

Dim first As UInt16 = BitConverter.ToUInt16(bytes, 0)

This is of course a bit slower than using bit shifts or division, but it handles the sign bit (the most significant bit) correctly, which you may have problems with using bit shift or division.

You can also get the first two bytes as a 16 bit unsigned number and assign it to an Integer:

Dim first As Integer = BitConverter.ToUInt16(bytes, 0)

(Getting a signed 16 bit number and assign to an Integer means that the sign bit would also be copied to the top 16 bits of the Integer, which is probably not desired.)

If you want the last two bytes (least significant) instead of the first two (most significant), just change the index in the ToUInt16/ToInt16 call from 0 to 2.

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

    Dim i As Integer = &HDEADBEEF
    Dim s16 As UShort
    s16 = i And &HFFFF 'BEEF

    'or
    s16 = (i >> 16) And &HFFFF 'DEAD

Upvotes: 0

sipsorcery
sipsorcery

Reputation: 30699

& it with 0xffff.

int input = 0xabcd;
int first2Bytes = input & 0xffff;

Upvotes: 0

Binary Worrier
Binary Worrier

Reputation: 51711

Assuming by first, you mean least value?

if My32BitNumber is an int

dim f16 as integer = &hFFFF and My32BitNumber

If you're actually looking at a 32 bit number e.g. Gee, what are the first 16 bits of DEADBEEF that would be the last four hex digits BEEF

Upvotes: 1

unwind
unwind

Reputation: 399889

That depends on what you mean by "first". Given a number, such as 0xdeadbeef, would you consider 0xdead or 0xbeef to be "first"?

If the former, divide the number by 65536 (as an integer). If the latter, compute the modulus to 65536.

This is of course also doable with binary operators such as shift/and, I'm just not sure sure how to express that in your desired language. I'm sure there will be other answers with more precise details.

Upvotes: 5

Related Questions