0

I have a string of hex that I want to convert to UTF-16L, as specified at https://en.wikipedia.org/wiki/GUID_Partition_Table under "Partition entries (LBA 2–33)". The string with hex has a fixed length of 72 bytes. I'm not sure what to do to convert it. I was thinking converting it to byte first then use Encoding.BigEndianUnicode Property.

Also when I tried to use Encoding.UTF8.GetChars then I got a lot of spaces in my result.

static void Main(string[] args)
{
    string hexString = "4200610073006900630020006400610074006100200070006100720074006900740069006F006E000000000000000000000000000000000000000000000000000000000000000000";
    int length = hexString.Length;
    byte[] bytes = new byte[length / 2];

    for (int i = 0; i < length; i += 2){
    bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
    }

    char[] chars = Encoding.UTF8.GetChars(bytes);

    string s = new string(chars);
    Console.WriteLine(s);
}

Prints this:

B a s i c d a t a p a r t i t i o n

(B\0a\0s\0i\0c\0 \0d\0a\0t\0a\0 \0p\0a\0r\0t\0i\0t\0i\0o\0n\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0)

enter image description here

Europa
  • 974
  • 12
  • 40
  • Does this answer your question? [.NET Convert from string of Hex values into Unicode characters (Support different code pages)](https://stackoverflow.com/questions/8608489/net-convert-from-string-of-hex-values-into-unicode-characters-support-differen) – Svirin Sep 06 '20 at 11:25
  • I tried that code but I got the error: "No data is available for encoding 932. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method." – Europa Sep 06 '20 at 11:28
  • Isn't that the same thing you are looking for? [.NET Convert from string of Hex values into Unicode characters](https://stackoverflow.com/questions/8608489/net-convert-from-string-of-hex-values-into-unicode-characters-support-differen) – abo Sep 06 '20 at 11:30
  • The code doesnt work because I get error "No data is available for encoding 932". Im in USA, I dont need Japanese letters. – Europa Sep 06 '20 at 11:34
  • Is this .net core project? .net core supports a limited number of encodings. – Svirin Sep 06 '20 at 11:39
  • You haven't shown how you're trying to convert `partitionNameBytes` into a string, but I see three problems to start with: 1) `len` is the length of the *string* - you should be converting that to half as many bytes (so you want half as many iterations). 2) You're currently trying to convert the first two characters of the string on every iteration. 3) You're not specifying anywhere that you want to use hex. I suspect you want to use `Convert.ToByte(string, int)`... – Jon Skeet Sep 06 '20 at 11:44
  • its C# WPF App (.NET Framework) – Europa Sep 06 '20 at 11:47
  • It is already encoded in UTF16LE, so you need Encoding.Unicode.GetString() – Hans Passant Sep 06 '20 at 12:32

0 Answers0