-2

i want to convert string to Byte[] in C# and with the help of previous topics i use this code : string s = "0a"; System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding(); byte[] b = encode.GetBytes(s); Console.WriteLine(b);

but when i run this code it only prints : " System.byte[]"

user3639111
  • 17
  • 1
  • 3

5 Answers5

0

If you want do this Console.WriteLine(b) it will prints the type of b which is System.Byte[]. In order to print the string stored in byte[] b, just make use of System.Text.ASCIIEncoding.GetString(byte[] b);

so in your case, encode.GetString(b); will get your string.

Jalal Mostafa
  • 984
  • 10
  • 23
0

You can use BitConverter class Check: http://msdn.microsoft.com/en-us/library/3a733s97(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

 System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
 byte[] b = encode.GetBytes(s);
 Console.WriteLine(BitConverter.ToString(b));
Ahmad Al Sayyed
  • 596
  • 5
  • 13
0

I think I may have finally deciphered your question. Are you trying to get the hex digits of your string into an array?

I'm assuming that you want to take 2-digit hex values from a string and convert each lot into bytes. If not, I'm as lost as everyone else. Please note that I have not included any error checking!

byte[] data = new byte[s.Length/2];
for(int i = 0; i < s.Length/2; ++i)
{
    byte val = byte.Parse(s.Substring(i*2,2), System.Globalization.NumberStyles.HexNumber);
    data[i] = val;
}

foreach(byte bv in data)
{
    Console.WriteLine(bv.ToString("X"));    
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
0

Your code already does the trick of converting string to byte, if your query is to print individual byte value, why not use a loop to print the value in byte array:

foreach (byte bb in b)
{
   Console.Write(Convert.ToInt32(bb));
}
saif
  • 370
  • 1
  • 3
  • 16
-1

That's because it's returning the type of the object that you are typing. If you want to print the content of the array, try this:

Arrays.toString(byteArray)
developer82
  • 13,237
  • 21
  • 88
  • 153