Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have got this code from somewhere to convert hex string to normal string.
But I cannot understand this. Can anybody explain this please ?
In this string, The first line takes each two characters from the string and convert it to byte.
But, I dont understand why they are assigning array to only half length of byte array ?

Sometimes it gets error too, i.e if Inputstring length is 350, byte length would be 175, and char length is 87.5, and char array is assigned to 87 only, thats not enough to hold all the characters in byte array.

C#
public static string HextoString(string InputText)
{

    byte[] bb = Enumerable.Range(0, InputText.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(InputText.Substring(x, 2), 16))
                     .ToArray();
    //return Convert.ToBase64String(bb);
    char[] chars = new char[bb.Length / sizeof(char)];
    System.Buffer.BlockCopy(bb, 0, chars, 0, bb.Length);
    return new string(chars);
}
Posted
Updated 30-Jun-14 22:40pm
v2
Comments
George Jonsson 1-Jul-14 11:13am    
What is your input string and what is the format of the string you want to return?
A basic input and output description.

Better to understand what you want to achieve than to try to fix random code you got from "somewhere".

Rob in Solution 4 is generally correct... However, if the string is hex encoded from a one byte per character encoding (ASCII for example) then it should be correct with an odd number of bytes.
Instead of dumping the bytes into the char array you should use the correct System.Text.Encoding object.
C#
public static string HextoString(string InputText)
{
 
    byte[] bb = Enumerable.Range(0, InputText.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(InputText.Substring(x, 2), 16))
                     .ToArray();
    return System.Text.Encoding.ASCII.GetString(bb);
    // or System.Text.Encoding.UTF7.GetString
    // or System.Text.Encoding.UTF8.GetString
    // or System.Text.Encoding.Unicode.GetString
    // or etc.
}
 
Share this answer
 
refer answer 4 in link[^] it is working.
 
Share this answer
 
Like so


C#
static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}



or


C#
string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
    // Convert the number expressed in base-16 to an integer.
    int value = Convert.ToInt32(hex, 16);
    // Get the character corresponding to the integral value.
    string stringValue = Char.ConvertFromUtf32(value);
    char charValue = (char)value;
    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
                        hex, value, stringValue, charValue);
}
 
Share this answer
 
 
Share this answer
 
OK, here we go.

Enumerable.Range - takes you from 0 to the length of the string
Where - ignores every other character
Select - takes two hexadecimal characters and converts them to byte
ToArray - creates a byte array from the result

So your hex string is now a byte array. I'd expect this to be returned, but it looks like they now convert this into a string.

Chars are two bytes in .NET so the divide is there to make sure both bytes in the char is used. As you say, they don't cater for the instance where the byte array has and odd number of characters in it. They are rounding down, but you need to round up.

Some brutal binary copy then dumps the byte array over the char array, and finally it is returned as a string which will be completely unintelligible.

The correct way to store a byte array is as a byte array, not an array of 2 byte chars half the size - I have no idea why you'd do this.
 
Share this answer
 
Comments
bernd-wechner 25-Mar-21 0:12am    
Hmmm, I try this and see:

Error	CS0103	The name 'Enumerable' does not exist in the current context

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900