[英]Convert an integer to a byte[] of specific length
我正在尝试创建一个函数(C#),该函数将使用2个整数(一个值变成byte [],一个值设置为数组的长度),并返回一个代表该值的byte []。 现在,我有一个仅返回长度为4的byte []的函数(我假设为32位)。
例如,类似InttoByteArray(0x01,2)的东西应该返回{0x00,0x01}的byte []。
有人对此有解决方案吗?
您可以使用以下内容
static public byte[] ToByteArray(object anyValue, int length)
{
if (length > 0)
{
int rawsize = Marshal.SizeOf(anyValue);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(anyValue, buffer, false);
byte[] rawdatas = new byte[rawsize * length];
Marshal.Copy(buffer, rawdatas, (rawsize * (length - 1)), rawsize);
Marshal.FreeHGlobal(buffer);
return rawdatas;
}
return new byte[0];
}
一些测试用例是:
byte x = 45;
byte[] x_bytes = ToByteArray(x, 1);
int y = 234;
byte[] y_bytes = ToByteArray(y, 5);
int z = 234;
byte[] z_bytes = ToByteArray(z, 0);
这将创建一个传入的任何大小的数组。如果只想返回字节数组,则应该很容易更改。 现在以更通用的形式
要获得示例中想要的内容,可以执行以下操作:
int a = 0x01;
byte[] a_bytes = ToByteArray(Convert.ToByte(a), 2);
您可以为此使用BitConverter实用程序类。 虽然我认为它不允许您在转换int时指定数组的长度。 但是您总是可以截断结果。
如果指定的长度小于4,请采用当前算法并从数组中截断字节;如果大于4,则用零填充。听起来像您已经对我解决了。
您想要一些循环,例如:
for(int i = arrayLen - 1 ; i >= 0; i--) {
resultArray[i] = (theInt >> (i*8)) & 0xff;
}
byte[] IntToByteArray(int number, int bytes)
{
if(bytes > 4 || bytes < 0)
{
throw new ArgumentOutOfRangeException("bytes");
}
byte[] result = new byte[bytes];
for(int i = bytes-1; i >=0; i--)
{
result[i] = (number >> (8*i)) & 0xFF;
}
return result;
}
它使用从低到高的字节从右到左填充result
数组。
byte byte1 = (byte)((mut & 0xFF) ^ (mut3 & 0xFF)); byte byte2 = (byte)((mut1 & 0xFF) ^ (mut2 & 0xFF));
引用自
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.