Skip to content

[C#] Convert a Byte to Hexadecimal

akaii de Shangaii

Asked Jan 26, 2006, 11:50 PM EST7 answers
Share
LinkedInX
Hi,

Everything is in the title I have an array in Byte[] which contains the ASCII code of a string but I have to give to my function a Byte[] that have Hex values of my string and not ASCII. How can I do that?

I have actually this code:

String abcd = "You got 1 voicemail";
Byte[] test = System.Text.ASCIIEncoding.UTF8.GetBytes(abcd);

I'm developping in C#.NET

7 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    Hi,

    C#
    try this , plz tell me if it fits ur req.
    
    private byte[] ConvertToHexArray(byte [] asciiData)
    {
    if(asciiData != null && asciiData.Length >0)
    {
    byte[] byteHexArray = new byte[asciiData.Length];
    for(int i = 0; i<asciiData.Length ; i ++)
    byteHexArray[i]= Byte.Parse(asciiData[i].ToString("X2"));
    return byteHexArray;
    }
    return null;
    }
    0
  • 0

    Hi,

    C#
    try this , plz tell me if it fits ur req.
    
    private byte[] ConvertToHexArray(byte [] asciiData)
    {
    if(asciiData != null && asciiData.Length >0)
    {
    byte[] byteHexArray = new byte[asciiData.Length];
    for(int i = 0; i<asciiData.Length ; i ++)
    byteHexArray[i]= Byte.Parse(asciiData[i].ToString("X2"));
    return byteHexArray;
    }
    return null;
    }
    0
  • 0
    there is a message error saying this:  Input string was not in a correct format.
    when it arrives at line:
    byteHexArray[i] = Byte.Parse(asciiData[i].ToString("X2"));

    This is the string I need to convert:  "You got 1 voicemail"
    0
  • 0
    Thanks Simon but the code you told me to look for is doing exactly the opposite of what I d like to do means I have a hexstring and I need to insert in my Byte array in Hexadecimal not in decimal.
    So if you know how I can do this it would help me a lot.
    0
  • 0

    What do you mean you have "characters in ascii bytes" and "characters in hex"? If you convert your ASCII's to bytes, they are numbers. So it doesent matter if you read them as decimal numbers or hex numbers.

    0
  • 0
    ok try this
    C#
    private byte[] ConvertToHexArray(byte [] asciiData){
    if(asciiData != null && asciiData.Length >0){
    byte[] byteHexArray = new byte[asciiData.Length];
    for(int i = 0; i<asciiData.Length ; i ++)
    byteHexArray[i]= Byte.Parse(asciiData[i].ToString("X2"),NumberStyles.HexNumber);
    
    return byteHexArray;
    }
    return null;
    }
    0