2

I have the following code:

var x = char.ConvertFromUtf32(0x0001F642);

var enc = new UTF32Encoding();
var bytes = enc.GetBytes(x);
var hex = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
    if (i % 4 != 3)
        continue;


    hex.AppendFormat("{0:x2}", bytes[i - 0]);
    hex.AppendFormat("{0:x2}", bytes[i - 1]);
    hex.AppendFormat("{0:x2}", bytes[i - 2]);
    hex.AppendFormat("{0:x2}", bytes[i - 3]);
}
var o = hex.ToString();
//results in 0001F642

This code tries to resolve the string which is in UTF-32 into hex decimal values, but I am facing the issue that the 4 Bytes representing the character are backwards. Is that a given or am I doing something wrong?

So without my i - 0, i - 1, i - 2, i - 3 and just formating the Byte Array as it is the result is

var x = char.ConvertFromUtf32(0x0001F642);

var enc = new UTF32Encoding();
var bytes = enc.GetBytes(x);
var hex = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
    hex.AppendFormat("{0:x2}", bytes[i]);
}
var o = hex.ToString();
//results is 42f60100
Heinzi
  • 167,459
  • 57
  • 363
  • 519
Rand Random
  • 7,300
  • 10
  • 40
  • 88

1 Answers1

3

There are, in fact, two (incompatible) variants of UTF-32: big-endian and little-endian.

By default, C# encodes UTF-32 as little endian (but it can encode big-endian UTF-32 as well).

Thus, your first code example creates the big-endian variant, your second example creates the little-endian variant.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • Thx for the answer and title update. Just out of curiosity you wrote in the title "Manually..." would there be an "Automatically..." way to do it? And could you give a comment on the Code itself, is that the best way to do what I want or is there another way you are aware of? – Rand Random Jun 26 '17 at 09:18
  • 1
    @RandRandom: If you don't mind dashes in your output, `BitConverter.ToString(bytes)` would be a bit shorter, but I think your code is fine as it is. You are right, the `Manually` could probably be removed. – Heinzi Jun 26 '17 at 09:24