Search code examples
c#.netbit-manipulationnfs

C# int to byte[]


I need to convert an int to a byte[] one way of doing it is to use BitConverter.GetBytes(). But im unsure if that matches the following specification:

An XDR signed integer is a 32-bit datum that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. Integers are declared as follows:

Source: RFC1014 3.2

How could i do a int to byte transformation that would satisfy the above specification?


Solution

  • In .NET Core 2.1+ and .NET 5+ you can use BinaryPrimitives.WriteInt32BigEndian() like this:

    int intVal = ...;
    byte[] bytes = new byte[4];
    BinaryPrimitives.WriteInt32BigEndian(bytes, intVal);
    
    • The conversion is done in one line.
    • It is a built in function.
    • It does not depend on the endianness of the computer.