How Do I: convert a String to Byte[]

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?
 
K

Ken Tucker [MVP]

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
 
R

Russell Mangel

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?
 
J

Jon Skeet [C# MVP]

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));
}
 

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