Home > Net >  Trying to convert hex to string but get lots of characters instead, works in python but not C#
Trying to convert hex to string but get lots of characters instead, works in python but not C#

Time:08-02

I'm trying to convert a hexadecimal value to a string. It works fine in python, but in C#, it's just a bunch of characters.

Hex: "293A4D48E43D5D1FBBFC8993DD93949F"

Python

>>> bytearray.fromhex('293A4D48E43D5D1FBBFC8993DD93949F');
bytearray(b'):MH\xe4=]\x1f\xbb\xfc\x89\x93\xdd\x93\x94\x9f')

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.Unicode.GetString(bb);
  // or System.Text.Encoding.UTF7.GetString
  // or System.Text.Encoding.UTF8.GetString
  // or System.Text.Encoding.Unicode.GetString
  // or etc.
}

HextoString('293A4D48E43D5D1FBBFC8993DD93949F');
// "):MH?=]▼????????"

CodePudding user response:

Python and C# decide what to do with unprintable characters in different ways. In the case of Python, it is printing their escape sequences (eg \xe4), but in C#, the unprintable characters are printed as question marks. You may want to convert the string to an escaped string literal before you print it.

CodePudding user response:

Hi my friend you can choose one of these ways :

  1. Convert Hex to String in Python:

    print(bytes.fromhex('68656c6c6f').decode('utf-8'))

2.Using codecs.decode:

import codecs

my_string = "68656c6c6f"
my_string_bytes = bytes(my_string, encoding='utf-8')

binary_string = codecs.decode(my_string_bytes, "hex")
print(str(binary_string, 'utf-8'))

3.Append hex to string

def hex_to_string(hex):
    if hex[:2] == '0x':
        hex = hex[2:]
    string_value = bytes.fromhex(hex).decode('utf-8')
    return string_value

hex_value = '0x737472696e67'
string = 'This is just a '   hex_to_string('737472696e67')

print(string)

Good luck (Arman Golbidi)

  • Related