Home > database >  Considering Endianness when converting bytes to string(hex)
Considering Endianness when converting bytes to string(hex)

Time:06-08

Is there any case when this test could fail? Would it fail on BigEndian machine? Is ByteArrayToHexString LittleEndian and why (chars seem to be written from left to right, so it must be BigEndian)?

[Fact]
public void ToMd5Bytes2_ValidValue_Converted()
{
    // Arrange
    // Act
    var bytes = new byte[] {16, 171, 205, 239};
    var direct = ByteArrayToHexString(bytes);
    var bitConverter = BitConverter.ToString(bytes).Replace("-", string.Empty);
    var convert = Convert.ToHexString(bytes);

    // Assert
    Assert.Equal(direct, bitConverter);
    Assert.Equal(bitConverter, convert);
}

public static string ByteArrayToHexString(byte[] Bytes)
{
    StringBuilder Result = new StringBuilder(Bytes.Length * 2);
    string HexAlphabet = "0123456789ABCDEF";

    foreach (byte B in Bytes)
    {
        Result.Append(HexAlphabet[(int)(B >> 4)]);
        Result.Append(HexAlphabet[(int)(B & 0xF)]);
    }

    return Result.ToString();
}

CodePudding user response:

Only multi-byte values are affected by endianness, like Int32.

Arrays of bytes are not - they're already a defined sequence of single bytes.
Of course, it matters how you retrieved this byte array - if it is the result of converting a multi-byte value, you must have done that conversion with the appropriate endianness. Otherwise you'd have to reverse each slice of your array which originally represented a multi-byte value.

Also, endianness does not happen on the bit level, a misconception I see every now and then.


In the comments, you mentioned the remarks sections of the BitConverter.ToString documentation:

All the elements of value are converted. The order of hexadecimal strings returned by the ToString method depends on whether the computer architecture is little-endian or big-endian.

Looking at the reference source, I do not see where endianness is having an effect on its operation on byte arrays. This comment is either outdated or misleading, and I've opened an issue on it.

  •  Tags:  
  • c#
  • Related