Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Byte array to Hexadecimal String


  • Please log in to reply
10 replies to this topic

#1 magarcan

magarcan

    Advanced Member

  • Members
  • PipPipPip
  • 43 posts

Posted 13 September 2011 - 09:14 AM

I'm receiving via UART some data that are saved into a byte array, the problem is that I want to print this data using Debug.Print one of the ways I've thought is converting this to an Hexadecimal string, but Micro Framework does not support BitConverter.ToString.

Any idea? Thanks!!

#2 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 13 September 2011 - 11:48 AM

Here is a function modified from the original I've written for the standard .Net framework.
I've tried to modify, but of sure has to be adapted again to fit the MF requirements.

public static string ToHex(
            byte[] buffer,
            char separator = ' ')
        {
            //get the buffer length
            int count = buffer.Length;

            if (count == 0)
            {
                //no data to display: return an empty string anyway
                return string.Empty;
            }
            else
            {
                int totalLength = (int)separator != 0
                    ? (count * 3 - 1)
                    : (count * 2);
                int currentLength = 0;
                var outputBuffer = new char[totalLength];

                //define a handler to transform one byte to a characters pair
                Action<int> convertByteToCharPair = (value) =>
                {
                    outputBuffer[currentLength] = _tbltohex[unchecked(value >> 4)];
                    outputBuffer[currentLength + 1] = _tbltohex[unchecked(value & 0x0F)];
                    currentLength += 2;
                };

                if ((int)separator != 0)
                {
                    //insert the first byte
                    convertByteToCharPair(buffer[0]);

                    //insert the remaining bytes
                    for (int index = 1; index < count; index++)
                    {
                        outputBuffer[currentLength++] = separator;
                        convertByteToCharPair(buffer[index]);
                    }
                }
                else
                {
                    //convert the whole buffer
                    for (int index = 0; index < count; index++)
                    {
                        convertByteToCharPair(buffer[index]);
                    }
                }

                return new String(outputBuffer);
            }
        }
Hope it helps.
Cheers
Biggest fault of Netduino? It runs by electricity.

#3 ColinR

ColinR

    Advanced Member

  • Members
  • PipPipPip
  • 142 posts
  • LocationCape Town, South Africa

Posted 13 September 2011 - 11:51 AM

private static string GetMACAddress()
{
	NetworkInterface ni = NetworkInterface.GetAllNetworkInterfaces()[0];
	char[] c = new char[17];
	byte b;

	for (byte y = 0, x = 0; y < 6; ++y, ++x)
	{
		b = (byte)(ni.PhysicalAddress[y] >> 4);
		c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
		b = (byte)(ni.PhysicalAddress[y] & 0xF);
		c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
		if (y < 5) c[++x] = '-';
	}

	return new string(c);
}

Should work as a base?

#4 baxter

baxter

    Advanced Member

  • Members
  • PipPipPip
  • 415 posts

Posted 13 September 2011 - 07:28 PM

Here is one from Jens Kühner's book,
Listing 4-16. Converting a Byte Value into a Hexadecimal String
public static string ByteToHex(byte B)
{
const string hex = "0123456789ABCDEF";
int lowNibble = b & 0x0F;
int highNibble = (b & 0xF0) >> 4;
string s = new string(new char[] { hex[highNibble], hex[lowNibble] });
return s;
}

And one in Visual Basic,
Public Function bytesToHexString(ByVal arr() As Byte,
                          Optional ByVal addSpc As Boolean = False) As String
        'by definition the string will have pairs of digits for the byte value
        Dim sb As New System.Text.StringBuilder()
        Dim separator As String = String.Empty
        If (addSpc) Then separator = " "
        For i As Integer = 0 To arr.Length - 1
            sb.Append(arr(i).ToString("x2") & separator)
        Next i
        Return sb.ToString.TrimEnd
    End Function


#5 Moskus

Moskus

    Advanced Member

  • Members
  • PipPipPip
  • 132 posts
  • LocationNorway

Posted 23 September 2011 - 09:04 AM

And one in Visual Basic,

Public Function bytesToHexString(ByVal arr() As Byte,
                          Optional ByVal addSpc As Boolean = False) As String
        'by definition the string will have pairs of digits for the byte value
        Dim sb As New System.Text.StringBuilder()
        Dim separator As String = String.Empty
        If (addSpc) Then separator = " "
        For i As Integer = 0 To arr.Length - 1
            sb.Append(arr(i).ToString("x2") & separator)
        Next i
        Return sb.ToString.TrimEnd
    End Function

Thanks! I've been looking for one. :)

#6 Moskus

Moskus

    Advanced Member

  • Members
  • PipPipPip
  • 132 posts
  • LocationNorway

Posted 23 September 2011 - 07:20 PM

I believe there's something wrong with the loop. This seems to be correct:
Public Function bytesToHexString(ByVal arr() As Byte, Optional ByVal addSpc As Boolean = False) As String
        Dim s As String = String.Empty
        Dim separator As String = String.Empty
        If addSpc Then separator = " "
        For i As Integer = arr.Length - 1 To 0 Step -1
            s &= arr(i).ToString("X1") & separator
        Next
        Return s
    End Function


#7 baxter

baxter

    Advanced Member

  • Members
  • PipPipPip
  • 415 posts

Posted 23 September 2011 - 11:34 PM

The function works as advertized. It simply converts a sequence of bytes (e.g. the values from 0 to array.length -1) to the hex representation of each byte. Running this,

'Testing byte to hex
 Dim byteArray() As Byte = {1, 2, 3, 4, 5, 15, 16, 17, 254, 255}
 Dim hex As String = bytesToHexString(byteArray, True)
 Debug.Print(hex)
produces the following which is correct,
01 02 03 04 05 0F 10 11 FE FF

Using ToString("X1") produces,

1 2 3 4 5 F 10 11 FE FF
I guess it is a matter of taste. I always format as pairs of digits to yield the 2 digit hex representation of a byte. It really doesn't matter because the receiving device will always eat the leading zero. However, if the receiver expects a 2 digit hex will it read 12 rather than 1 without the spaces. I have a uOLED device that wants hex pairs. From your loop, it seems that you wish to generate the string backwards.

Baxter

#8 Moskus

Moskus

    Advanced Member

  • Members
  • PipPipPip
  • 132 posts
  • LocationNorway

Posted 24 September 2011 - 08:41 AM

The function works as advertized.

For that sample, yes. I agree. I messed up.

But I'm confused (and it's not the first time). Try this:
Dim hex As Integer = &H2AF3
        Console.WriteLine("Hex: " & hex)
        Console.WriteLine("BytesToHexString: " & bytesToHexString(BitConverter.GetBytes(hex)))


Which gives...
Hex: 10995
BytesToHexString: F32A0000


Shouldn't that be:

00002AF3
instead? Or is it the BitConverter that's off?

#9 baxter

baxter

    Advanced Member

  • Members
  • PipPipPip
  • 415 posts

Posted 24 September 2011 - 06:41 PM

I think this is related to little-endian and big-endian. See the example toward the middle of this page,

http://msdn.microsof...tconverter.aspx

Also, this gives the same answer as bytesToHexString,
byte[] array = new byte[] { 0x01, 0x02, 0x03, 0x04 }; 
string s = System.BitConverter.ToString(array);  
// Result: s = "01-02-03-04"
The problem is bitconverter is not working with Netduino.

Baxter

#10 Moskus

Moskus

    Advanced Member

  • Members
  • PipPipPip
  • 132 posts
  • LocationNorway

Posted 24 September 2011 - 08:02 PM

I think this is related to little-endian and big-endian. See the example toward the middle of this page,
http://msdn.microsof...tconverter.aspx

Ah, thank you! I'm learning something new every day! :)


The problem is bitconverter is not working with Netduino.

Yeah, I haven't got around that problem yet. If you have any pointers I take all I can get. ;)

#11 baxter

baxter

    Advanced Member

  • Members
  • PipPipPip
  • 415 posts

Posted 24 September 2011 - 09:35 PM

Look here, http://forums.netdui...8-bitconverter/ Bitconverter is a very handy function, but you can always write a workaround to perform the same operation in VB code. Baxter




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.