tags:

views:

305

answers:

4
+2  Q: 

VB.NET and bytes

I'm a little confused as to bytes. I can open a file in a hex editor and know that each 2 digits is a byte, they are 8 digits in binary correct? How are they stored in arrays in VB.NET? So if I have

Dim xx() as byte =

What would I put after the equals? The hex digits from the hex editor?

(This is just a program I'm not going to save, basically I don't want to open files to get etc. I want to put in the bytes in the code.)


Thanks everyone for your answers (on new years eve too :) )

+5  A: 

You need to write the bytes as a hexadecimal numbers, like this:

Dim xx() As Byte = { &H43, &h44, &h4C }

You can also write bytes as regular decimal numbers, like this:

Dim xx() As Byte = { 67, 68, 76 }
SLaks
Jonathan
I think it is terminating at the first zero in your array.
ChaosPandion
The ` they will behave unexpectedly.
SLaks
It just isn't a string in any kind of conventional encoding. GIGO.
Hans Passant
If you want to print a content of a byte array as a sequence of hex numbers, one per byte (as hex editor shows it), use `BitConverter.ToString()`. When you use `Encoding.ASCII.GetString()`, you get a string consisting of characters, each of which has ASCII code corresponding to one byte.
Pavel Minaev
+1  A: 

The syntax for hex values in VB uses &H ie

    Dim xx() As Byte = {&HAB, &H2C, &HFF }

see http://msdn.microsoft.com/en-us/library/s9cz43ek.aspx

RichardHowells
A: 

A byte is represented in binary as eight bits. Binary is base two, so with eight bits you can store a maximum of 256 values. When you use a hex editor to view a byte, you see two digits because the hex values are in base sixteen. To show 256 values requires two hex digits (maximum values per hex digit = sixteen, 256 = 16 x 16). As mentioned above, the syntax for representing a hex value is &H--, where -- is hex and &H identifies the value as hex. If you're familiar with C/C++, this was represented as 0x--.

As noted, a character is not necessarily a byte. The ASCII characters occupy one byte on some systems (DOS, etc.), but as Windows implements Unicode, a character can be a multibyte value. A good example of this would be a Kanji (Japanese) character/glyph.

Happy coding,

Scott

Scott Davies
+1  A: 

Be careful not to confuse bytes for characters. In VB.NET, a character often takes up several bytes.

Joel Coehoorn