How Do I: convert a String to Byte[]

  • Thread starter Thread starter Russell Mangel
  • Start date Start date
R

Russell Mangel

// Need help converting String to Byte[]

// How do I get this String in a Byte Array
String strBytes = "FFD9FFD8";

// Like this...
Byte[] Bytes = {0xFF, 0xD9, 0xFF, 0xD8};

// This is no good, as it converts each character to hex
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
Byte[] bytes = ascii.GetBytes(strBytes);

// This is no good
foreach (Byte b in bytes)
{
Console.Write("{0:X2} ", b);
}

Console.WriteLine("\n");
// This is what I want
foreach(Byte bb in Bytes)
{
Console.Write("{0:X2} ", bb);
}

// Can Someone Help?
 
Hi,

Dim strBytes As String = "FFD9FFD8"

Dim arBytes() As Byte

arBytes = System.Text.Encoding.Default.GetBytes(strBytes)

Dim x As Integer

For x = 0 To arBytes.GetUpperBound(0)

Debug.WriteLine(arBytes(x))

Next

Ken
 
Thanks for the reply, however your code also does not work.
Your code does exactly what my code does.
It converts each character 'F' 'F' 'D' '9' 'F' 'F' 'D' '8' and puts 8 bytes
in array.
I need to get 'FF' 'D9' FF' 'D8' and put 4 bytes in array.

This seemed trivial when I first tried... Back to drawing board...
Russell Mangel
Las Vegas, NV

Ken Tucker said:
Hi,

Dim strBytes As String = "FFD9FFD8"

Dim arBytes() As Byte

arBytes = System.Text.Encoding.Default.GetBytes(strBytes)

Dim x As Integer

For x = 0 To arBytes.GetUpperBound(0)

Debug.WriteLine(arBytes(x))

Next

Ken

----------------------

Russell Mangel said:
// Need help converting String to Byte[]

// How do I get this String in a Byte Array
String strBytes = "FFD9FFD8";

// Like this...
Byte[] Bytes = {0xFF, 0xD9, 0xFF, 0xD8};

// This is no good, as it converts each character to hex
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
Byte[] bytes = ascii.GetBytes(strBytes);

// This is no good
foreach (Byte b in bytes)
{
Console.Write("{0:X2} ", b);
}

Console.WriteLine("\n");
// This is what I want
foreach(Byte bb in Bytes)
{
Console.Write("{0:X2} ", bb);
}

// Can Someone Help?
 
Russell Mangel said:
// Need help converting String to Byte[]

// How do I get this String in a Byte Array
String strBytes = "FFD9FFD8";

// Like this...
Byte[] Bytes = {0xFF, 0xD9, 0xFF, 0xD8};


byte[] Bytes = new byte[strBytes.Length/2];
for (int i=0; i < strBytes.Length; i+=2)
{
Bytes = Byte.Parse (strBytes.Substring (i, 2));
}
 
Back
Top