简体   繁体   English

如何将int转换为byte的数组然后返回?

[英]How do I convert a int to an array of byte's and then back?

I need to send an integer through a NetworkStream. 我需要通过NetworkStream发送一个整数。 The problem is that I only can send bytes. 问题是我只能发送字节。 Thats why I need to split the integer in four byte's and send those and at the other end convert it back to a int. 这就是为什么我需要将整数分成四个字节并发送它们,另一端将其转换回int。

For now I need this only in C#. 现在我只需要在C#中使用它。 But for the final project I will need to convert the four bytes to an int in Lua. 但是对于最终项目,我需要将四个字节转换为Lua中的int。

[EDIT] How about in Lua? [编辑]在Lua怎么样?

BitConverter is the easiest way, but if you want to control the order of the bytes you can do bit shifting yourself. BitConverter是最简单的方法,但如果你想控制字节的顺序,你可以自己进行位移。

int foo = int.MaxValue;
byte lolo = (byte)(foo & 0xff);
byte hilo = (byte)((foo >> 8) & 0xff);
byte lohi = (byte)((foo >> 16) & 0xff);
byte hihi = (byte)(foo >> 24);

Also.. the implementation of BitConverter uses unsafe and pointers, but it's short and simple. 另外..BitConverter的实现使用不安全和指针,但它简短而简单。

public static unsafe byte[] GetBytes(int value)
{
   byte[] buffer = new byte[4];
   fixed (byte* numRef = buffer)
   {
      *((int*) numRef) = value;
   }
   return buffer;
}

Try 尝试

BitConverter.GetBytes() BitConverter.GetBytes()

http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

Just keep in mind that the order of the bytes in returned array depends on the endianness of your system. 请记住,返回数组中字节的顺序取决于系统的字节顺序。

EDIT: As for the Lua part, I don't know how to convert back. 编辑:至于Lua部分,我不知道如何转换回来。 You could always multiply by 16 to get the same functionality of a bitwise shift by 4. It's not pretty and I would imagine there is some library or something that implements it. 您总是可以乘以16来获得与按位移位相同的功能。它不是很漂亮,我会想象有一些库或某些东西可以实现它。 Again, the order to add the bytes in depends on the endianness, so you might want to read up on that 同样,添加字节的顺序取决于字节顺序,因此您可能想要阅读它

Maybe you can convert back in C#? 也许你可以转换回C#?

Here are some functions in Lua for converting a 32-bit two's complement number into bytes and converting four bytes into a 32-bit two's complement number. 以下是Lua中的一些函数,用于将32位二进制补码数转换为字节,并将四个字节转换为32位二进制补码数。 A lot more checking could/should be done to verify that the incoming parameters are valid. 可以/应该进行更多检查以验证传入参数是否有效。

-- convert a 32-bit two's complement integer into a four bytes (network order)
function int_to_bytes(n)
  if n > 2147483647 then error(n.." is too large",2) end
  if n < -2147483648 then error(n.." is too small",2) end
  -- adjust for 2's complement
  n = (n < 0) and (4294967296 + n) or n
  return (math.modf(n/16777216))%256, (math.modf(n/65536))%256, (math.modf(n/256))%256, n%256
end

-- convert bytes (network order) to a 32-bit two's complement integer
function bytes_to_int(b1, b2, b3, b4)
  if not b4 then error("need four bytes to convert to int",2) end
  local n = b1*16777216 + b2*65536 + b3*256 + b4
  n = (n > 2147483647) and (n - 4294967296) or n
  return n
end

print(int_to_bytes(256)) --> 0 0 1 0
print(int_to_bytes(-10)) --> 255 255 255 246
print(bytes_to_int(255,255,255,246)) --> -10

For Lua, check out Roberto's struct library. 对于Lua,请查看Roberto的结构库。 (Roberto is one of the authors of Lua.) It is more general than needed for the specific case in question, but it isn't unlikely that the need to interchange an int is shortly followed by the need to interchange other simple types or larger structures. (罗伯托是Lua的作者之一。)对于具体案例来说,它比一般情况更为通用,但是不一定需要交换一个int ,之后需要交换其他简单类型或更大的类型。结构。

Assuming native byte order is acceptable at both ends (which is likely a bad assumption, incidentally) then you can convert a number to a 4-byte integer with: 假设本地字节顺序在两端都是可接受的(这可能是一个错误的假设,偶然),那么您可以将数字转换为4字节整数:

buffer = struct.pack("l", value)

and back again with: 再回来:

value = struct.unpack("l", buffer) value = struct.unpack(“l”,buffer)

In both cases, buffer is a Lua string containing the bytes. 在这两种情况下, buffer都是包含字节的Lua字符串。 If you need to access the individual byte values from Lua, string.byte is your friend. 如果你需要从Lua访问各个字节值, string.byte就是你的朋友。

To specify the byte order of the packed data, change the format from "l" to "<l" for little-endian or ">l" for big-endian. 要指定打包数据的字节顺序,请将格式从"l"更改为"<l"对于little-endian)或">l"对于big-endian)。

The struct module is implemented in C, and must be compiled to a DLL or equivalent for your platform before it can be used by Lua. struct模块在C中实现,在Lua可以使用之前,必须将其编译为您的平台的DLL或等效项。 That said, it is included in the Lua for Windows batteries-included installation package that is a popular way to install Lua on Windows systems. 也就是说,它包含在Lua for Windows电池包含的安装包中,这是在Windows系统上安装Lua的常用方法。

调查BinaryWriter / BinaryReader类

Convert an int to a byte array and display : BitConverter ... 将int转换为字节数组并显示:BitConverter ...

www.java2s.com/Tutorial/CSharp/0280__Development/Convertaninttoabytearrayanddisplay.htm www.java2s.com/Tutorial/CSharp/0280__Development/Convertaninttoabytearrayanddisplay.htm

Integer to Byte - Visual Basic .NET answers 整数到字节 - Visual Basic .NET的答案

http://bytes.com/topic/visual-basic-net/answers/349731-integer-byte http://bytes.com/topic/visual-basic-net/answers/349731-integer-byte

How to: Convert a byte Array to an int (C# Programming Guide) 如何:将字节数组转换为int(C#编程指南)

http://msdn.microsoft.com/en-us/library/bb384066.aspx http://msdn.microsoft.com/en-us/library/bb384066.aspx

As Nubsis says, BitConverter is appropriate but has no guaranteed endianness. 正如Nubsis所说, BitConverter是合适的,但没有保证的字节顺序。

I have an EndianBitConverter class in MiscUtil which allows you to specify the endianness. 我在MiscUtil中有一个EndianBitConverter类,它允许您指定字节顺序。 Of course, if you only want to do this for a single data type ( int ) you could just write the code by hand. 当然,如果您只想为单个数据类型( int )执行此操作,则可以手动编写代码。

BinaryWriter is another option, and this does guarantee little endianness. BinaryWriter是另一种选择,这确实保证了很少的字节顺序。 (Again, MiscUtil has an EndianBinaryWriter if you want other options.) (同样,如果你想要其他选项,MiscUtil有一个EndianBinaryWriter 。)

To convert to a byte[]: 要转换为byte []:

BitConverter.GetBytes(int) BitConverter.GetBytes(INT)

http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

To convert back to an int: 要转换回int:

BitConverter.ToInt32(byteArray, offset) BitConverter.ToInt32(byteArray,offset)

http://msdn.microsoft.com/en-us/library/system.bitconverter.toint32.aspx http://msdn.microsoft.com/en-us/library/system.bitconverter.toint32.aspx

I'm not sure about Lua though. 我不确定Lua。

If you are concerned about endianness use John Skeet's EndianBitConverter. 如果你担心字节顺序,请使用John Skeet的EndianBitConverter。 I've used it and it works seamlessly. 我已经使用它了,它可以无缝地工作。

C# supports their own implementation of htons and ntohs as: C#支持自己实现的htons和ntohs:

But they only work on signed int16, int32, int64 which means you'll probably end up doing a lot of unnecessary casting to make them work, and if you're using the highest order bit for anything other than signing the integer, you're screwed. 但它们只能在signed int16,int32,int64上工作,这意味着你可能最终会进行大量不必要的转换以使它们工作,如果你使用最高位除了签署整数以外的任何东西,你'重新拧紧。 Been there, done that. 去过也做过。 ::tsk:: ::tsk:: Microsoft for not providing better endianness conversion support in .NET. :: tsk ::: tsk :: Microsoft因为没有在.NET中提供更好的字节顺序转换支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM