0

I have a byte array containing value like this: byte[] data={0x04,0x00};

I need to convert it to a string a print it as str_data=0x400

But when i convert this to string the data is printed as 40 where last 0x00 is considered as only 0.

I am new to C# and I am struggling to solve this. Please help.

sunisiha
  • 57
  • 6
  • 2
    Can you show the code you are using to convert it to a string? – juharr Apr 17 '15 at 11:30
  • 1
    The actual types you want are a little unclear. title says int[] the desired variable name seems to be string but contains an int... please update problem description – FrankB Apr 17 '15 at 11:31
  • BitConverter.ToInt16() does that. Or a MemoryStream to store the bytes and BinaryReader to convert. How you format the value when you print them is separate, use the X format specifier to produce a hex string. – Hans Passant Apr 17 '15 at 12:10
  • Initially I was trying this code to covert byte array to int array and then printing it as string `int[] intArray = new int[0]; byte[] byteArray = new byte[0]; intArray = byteArray.Select(x => (int)x).ToArray(); ApplicationLogger.WriteMsg("Print : " + intArray.ToString());` – sunisiha Apr 17 '15 at 13:51

1 Answers1

1

Your question is a bit unclear, but I think what you want is the X2 format specifier for bytes, which will print your bytes as two hex digits, e.g.:

byte b = 0x40;
Console.WriteLine( b.ToString( "X2" ) ); // Prints '40'

Convert each of your bytes into a string (with e.g. LINQ's Select method), then join them and add the "0x" prefix.

Solal Pirelli
  • 1,199
  • 9
  • 21
  • ...except for the very first byte, where you only seem to need x instead of x2; or get rid of the (possible) leading zero afterwards... – FrankB Apr 17 '15 at 12:07
  • I got the answer here : http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa – sunisiha Apr 17 '15 at 13:47
  • Thank you for your answer. I used following snippet `StringBuilder hex = new StringBuilder(byteArray.Length * 2); foreach (byte b in byteArray) hex.AppendFormat("{0:x2}", b);` – sunisiha Apr 17 '15 at 13:48