locked
byte array to string RRS feed

  • Question

  •  

    I have a byte array looking like this: {0x27, 0x2, 0x10, 0x81}. I want to convert it to a string looking like this:

    "2721081". How do I accomplish this? Thanks in advance //Biff

    Tuesday, February 19, 2008 12:12 PM

Answers

  • I suppose your byte array is not encoded in any manner... That is: you only want a string with all ascii codes of your bytes in hexa format:

     

    Code Snippet

    private string ByteArrayToString(byte[] data)

    {

    StringBuilder sb = new StringBuilder();

    foreach (byte b in data)

    {

    sb.Append(b.ToString("X"));

    }

    return sb.ToString();

    }

     

     

    If you call the method that way:

     

    Code Snippet

    byte[] values = { 0x1, 0x2, 0x10, 0xFF };

    string val = ByteArrayToString(values);

     

    The returned string will be "1210FF"

     

    Greetings,

    edu

    Tuesday, February 19, 2008 1:03 PM

All replies

  • Have you looked at Base64 encoding?

    string result = Convert.ToBase64String(byteArray);
    Tuesday, February 19, 2008 12:38 PM
  •  Necromancer768 wrote:

     

    I have a byte array looking like this: {0x27, 0x2, 0x10, 0x81}. I want to convert it to a string looking like this:

    "2721081". How do I accomplish this? Thanks in advance //Biff

     

    There are a numerous methods within the Microsoft..VisualBasic.Conversion class.

     

    public static string Hex(byte Number)

    Member of Microsoft.VisualBasic.Conversion

    Summary:

    Returns a string representing the hexadecimal value of a number.

    Parameters:

    Number: Required. Any valid numeric expression or String expression.

    Return Values:

    Returns a string representing the hexadecimal value of a number.

     

     

    Rudedog

    Tuesday, February 19, 2008 1:00 PM
  • I suppose your byte array is not encoded in any manner... That is: you only want a string with all ascii codes of your bytes in hexa format:

     

    Code Snippet

    private string ByteArrayToString(byte[] data)

    {

    StringBuilder sb = new StringBuilder();

    foreach (byte b in data)

    {

    sb.Append(b.ToString("X"));

    }

    return sb.ToString();

    }

     

     

    If you call the method that way:

     

    Code Snippet

    byte[] values = { 0x1, 0x2, 0x10, 0xFF };

    string val = ByteArrayToString(values);

     

    The returned string will be "1210FF"

     

    Greetings,

    edu

    Tuesday, February 19, 2008 1:03 PM
  •  

    Whe the returned string still have the hexadecimal characters "F" it is expected to display it in decimal notation.
    Thursday, February 21, 2008 4:10 AM