是否有一个内置函数来扩展byte[],在开始处留下零

本文关键字:开始 内置 有一个 函数 byte 扩展 是否 | 更新日期: 2023-09-27 18:04:33

我已经有了这个代码

BitConverter.GetBytes(width).CopyTo(resultBytes, 0);

如果宽度是12,它返回一个字节而不是4,是否有一个内置的函数来调整数组的大小,在开始时留下0输出[0,0,0,12]而不是[12]。

是否有一个内置函数来扩展byte[],在开始处留下零

width的类型是什么?位转换器只是将类型转换为适当大小的数组。如果你输入

long  x = 1 ;
int   y = 2 ;
short z = 3 ;
byte[] x_bytes = BitConverter.GetBytes(x) ;
byte[] y_bytes = BitConverter.GetBytes(y) ;
byte[] z_bytes = BitConverter.GetBytes(z) ;

您将分别得到8字节、4字节和2字节数组。您可以转换为所需的类型:

byte[] bytes = BitConverter.GetBytes( (int) x ) ;

如果你说

byte[] bytes = BitConverter.GetBytes(1) ;

你将得到一个4字节的数组:一个无后缀的整数字面值的类型是最小的类型,将适合,按优先顺序:int, uint, long, ulong。如果字面值有后缀,它将是由后缀指定的类型(例如,1L将给你一个8字节的long)。

如果要转换表达式,例如:

byte[] bytes = BitConverter.GetBytes( ((3*x + 2&y + z) << 3 ) & 5L ) ;

被转换的当然是表达式求值产生的类型。

您需要将width转换为int以获得4字节,因为GetBytes()的结果依赖于传入的类型:

    BitConverter.GetBytes((int)width).CopyTo(resultBytes, 0);

也许这是最简单的解决方案,但是Array.Reverse:

BitConverter.GetBytes(4).CopyTo(resultBytes, 0); // [4, 0, 0, 0]
Array.Reverse(resultBytes); // [0, 0, 0, 4]