String to Byte

  • Thread starter Thread starter Aaron
  • Start date Start date
A

Aaron

How converts a string to a byte and then add it to a byte array? I
tried 2 different methods and both failed to work.

For example:
Dim A as string
Dim B(2) as Byte 'array (from 0 to 2)

A="7B"

B(0) = convert.Tobyte(A)'ERROR1
B(1) = Encoding.ASCII.GetBytes(A)'Error 2
B(2) = Hex("00")


'Error msg1
'An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll

'Additional information: Input string was not in a correct format.
'-----------

'Error msg 2
'Value of type '1-dimensional array of Byte' cannot be converted to
'Byte'.
 
Aaron said:
How converts a string to a byte and then add it to a byte array? I
tried 2 different methods and both failed to work.

For example:
Dim A as string
Dim B(2) as Byte 'array (from 0 to 2)

A="7B"

B(0) = convert.Tobyte(A)'ERROR1

B(0) = convert.Tobyte(A, 16)
 
The GetBytes method is what you are looking for.
If you want GetBytes to put the result into an exisitng array, you'll
need to use the overload which specifies begin index and a count of
characters to convert:

Encoding.ASCII.GetBytes(A, 0, 2, B, 0)
B(2) = 0

If you want a more generic solution, use GetByteCount to see how many
bytes it will take to store the string.

HTH,
 
Aaron said:
How converts a string to a byte and then add it to a byte array? I
tried 2 different methods and both failed to work.

For example:
Dim A as string
Dim B(2) as Byte 'array (from 0 to 2)

A="7B"

B(0) = convert.Tobyte(A)'ERROR1
B(1) = Encoding.ASCII.GetBytes(A)'Error 2
B(2) = Hex("00")


'Error msg1
'An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll

'Additional information: Input string was not in a correct format.
'-----------

'Error msg 2
'Value of type '1-dimensional array of Byte' cannot be converted to
'Byte'.

Dim A as String
Dim B() as Byte

A="7b"
B=System.Text.Encoder.ASCI.GetBytes(A)


B is now:
B(0):7
B(1):b

And that's all there is to it :)

HTH
Sueffel
 
You have to know that this doesn't add hex values into the array..

B(0): 7 will translate to the hex value: 37
B(1): B will translate to the hex value: 42
B(2): Hex("00") will translate to the hex value: 30 30

I'm also looking for a way to fill an array with the hex values as written
in the string..
 
Ah Ha! This is a different problem. You apparently have a string like
"00A1B2C3D4FF" and want a byte array containing B(0) = 00, B(1) = A1...
B(5) = FF

So....
<code>
Dim instring As String = "00A1B2C3D4FF"

Dim B(instring.Length / 2) As Byte

For i As Integer = 0 To (instring.Length / 2) - 1

B(i) = System.Convert.ToByte(instring.Substring(i * 2, 2), 16)

Next

</code>

the convert.tobyte takes two arguments: a string and a base (in your case
16 or hexadecimal)



Hope this helped,

Ot
 
Back
Top