Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#netcore2.0整数到字节转换,支持endianess_C#_.net Core_Endianness - Fatal编程技术网

c#netcore2.0整数到字节转换,支持endianess

c#netcore2.0整数到字节转换,支持endianess,c#,.net-core,endianness,C#,.net Core,Endianness,我正在开发一个信封加密库,其中信封结构是字节数组的组合 keyAlias length , keyAlias , IVBytes, cipherBytes = [int][keyAlias][IV][cipherBytes] 当我存储int的前4个字节以从信封字节检索keyAlias的长度时,我会寻找int到字节和返回int的正确处理方法 假设:我决定总是将int字节以小端格式存储在信封字节中 执行以下int到bytes的正确方法。我没有办法测试它,因为我无法访问Big Endian机器 [

我正在开发一个信封加密库,其中信封结构是字节数组的组合

keyAlias length , keyAlias , IVBytes, cipherBytes = 
[int][keyAlias][IV][cipherBytes]
当我存储int的前4个字节以从信封字节检索keyAlias的长度时,我会寻找int到字节和返回int的正确处理方法

假设:我决定总是将int字节以小端格式存储在信封字节中

执行以下int到bytes的正确方法。我没有办法测试它,因为我无法访问Big Endian机器

[Fact]
public void IntToByteConverion_ShouldConvertBack2()
{
    var intBytes = 2.ToLittleEndianBytes();

    //Store intBytes to Database or AWS S3
    // Retrive back the bytearray and convert to int32.

    int intValue = intBytes.FromLittleEndianBytes();

    Assert.Equal(2, intValue);
}

public static byte[] ToLittleEndianBytes(this int value)
{
    if (BitConverter.IsLittleEndian)
    return BitConverter.GetBytes(value);
    else
    {
        var bigEndianBytes = BitConverter.GetBytes(value);
        Array.Reverse(bigEndianBytes);// Converted to LittleEndian
        return bigEndianBytes;
    }
}

public static Int32 FromLittleEndianBytes(this byte[] littleEndianBytes)
{
    if (BitConverter.IsLittleEndian)
    return BitConverter.ToInt32(littleEndianBytes, 0);
    else
    {
        Array.Reverse(littleEndianBytes);// Converted to big endian as machine CPU is big endian
        return BitConverter.ToInt32(littleEndianBytes, 0);
    }
}

你所做的很有效。要测试它,您可以替换:

if(BitConverter.IsLittleEndian)
与:

并使用调试器检查字节是否实际反转。如果是这样的话(它是这样的),那么它就工作了,因为小端和大端的区别在于字节顺序

只需对您的代码发表一条评论(这可能更多地属于以下范围):

使用:

Array.Reverse(littleEndianBytes);
在方法上:

Int32 FromLittleEndianBytes(this byte[] littleEndianBytes)

不是最佳做法,因为您正在反转发送给该方法的字节数组。该方法的用户可能不会想到它,也可能会感到困惑。

在我所述的问题中,我使用LittleEndian对myint进行编码,并将其作为字节传输或存储在db中。若你们参考这篇文章:它说常见的惯例是通过网络以大端方式发送字节。由于我没有遵循这个惯例,我只想确认这不会导致任何错误。
Int32 FromLittleEndianBytes(this byte[] littleEndianBytes)