Converting integer to bytes in VB.NET

G

Guest

Hallo

I am trying to convert an integer into 4 bytes. In C# this can be done as follows

BitmapData[0x02] = (byte) nBytes
BitmapData[0x03] = (byte) (nBytes >> 8)
BitmapData[0x04] = (byte) (nBytes >> 16)
BitmapData[0x05] = (byte) (nBytes >> 24)

How can I do this in VB.NET

Nigel..
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hello Nigel,

VB. NET has the same bit shiftin operators: << and >>
To quote the corresponding MSDN example:

---------------------------------------------------------------------
Dim Pattern As Short = 192 ' Bit pattern is 0000 0000 1100 0000.
Dim Result1, Result2, Result3, Result4, Result5 As Short
Result1 = Pattern << 0 ' Result is 192 (0000 0000 1100 0000).
Result2 = Pattern << 4 ' Result is 3072 (0000 1100 0000 0000).
Result3 = Pattern << 9 ' Result is -32768 (1000 0000 0000 0000).
Result4 = Pattern << 17 ' Result is 384 (0000 0001 1000 0000).
Result5 = Pattern << -1 ' Result is 0 (shifted 15 places to left).
---------------------------------------------------------------------

You can also refer to the following MSDN topic:

"Bit Shift Operators"

in the "Visual Basic Language Reference" section.
 
G

Guest

Thanks Dmitriy

This is really helpfull, I was looking everywhere for these shift operators.

If I am starting with a normal integer, whats the best way to chop this down into Short integers or bytes

Nigel...
 
D

Dmitriy Lapshin [C# / .NET MVP]

Speaking of bytes, you might consider the BitConverter class as the
ready-made solution

Nigel Findlater said:
Thanks Dmitriy,

This is really helpfull, I was looking everywhere for these shift operators..

If I am starting with a normal integer, whats the best way to chop this
down into Short integers or bytes?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top