Search code examples
c#unicodehextype-conversionulong

ulong to hex conversion clarification


I have a reference program which I got online. In that variable data64 is defined as ulong type. Which they're converting to unicode and displaying in a textbox like this:

TextBox1.AppendText = Rxmsg.data64.ToString("X");

The actual value of data64 is "12288092688749907974". While it displays in textbox the value is "AA88133200035006". I thought it's a simple decimal to hex conversion. So I converted the data64 value to hex but I was wrong. Can anyone please clarify me how the above conversion was made? It's related to one of my projects. It would be very useful for me to proceed further.


Solution

  • reason is the Endianness of the display

    IsLittleEndian Yes: 06-50-03-00-32-13-88-AA

    IsLittleEndian No: AA-88-13-32-00-03-50-06

    fiddle demo and wikipedia link

    using System;
    
    namespace ConsoleApplication1
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var value = 12288092688749907974u;
                var bytes = BitConverter.GetBytes(value);
    
                Console.Write(BitConverter.IsLittleEndian ? "IsLittleEndian Yes" : "IsLittleEndian No");
                Console.WriteLine(" Value " + BitConverter.ToString(bytes));
    
                Array.Reverse(bytes);
                Console.Write(BitConverter.IsLittleEndian ? "IsLittleEndian No" : "IsLittleEndian Yes");
                Console.WriteLine(" Value " + BitConverter.ToString(bytes));
    
                Console.Read();
            }
        }
    }