我想用十六进制数转换一个十进制数,然后先用LSB通过串口发送。 我试过这个
I want to convert a decimal number in hexadecimal number and send through serial port with LSB first. I tried this
Int32 decValue = 1234056789; byte[] testBytes = new byte[4]; testBytes [0] = (byte)(decValue & 0x000000FF); testBytes [1] = (byte)((decValue >> 8) & 0x000000FF); testBytes [2] = (byte)((decValue >> 16) & 0x000000FF); testBytes [3] = (byte)((decValue >> 24) & 0x000000FF);testBytes [0]是否包含LSB中的字节第一个或MSB优先???
Is testBytes[0] contains bytes in LSB first or MSB first???
推荐答案严格来说,它取决于连接到RS-232电缆另一端的设备的要求。 Windows使用little-endian格式(最低有效字节优先);我会说,大多数系统都是这样做的。但是,这不是一个规则; big-endian也被使用。例如,所谓的标准网络订单是big-endian。 请参阅: en.wikipedia/wiki/Endianness [ ^ ]。
这是测试方法来自msdn: msdn.microsoft/en-us/library/bb384066 .aspx [ ^ ] This is the way to test taken from msdn: msdn.microsoft/en-us/library/bb384066.aspx[^] byte[] bytes = { 0, 0, 0, 25 }; int i = BitConverter.ToInt32(bytes, 0); Console.WriteLine("int: {0}", i);
如果这打印25,那么你的计算机是big-endian - 你首先发送testBytes [3]。 如果它不打印25然后发送testBytes [ 0]首先。 但是有一个对endian_ness BitConverter.IsLittleEndian的测试。所以你可以写:
If this prints 25 then your computer is big-endian - you send testBytes [3] first. If it does not print 25 then send testBytes [0] first. There is however a test for endian_ness BitConverter.IsLittleEndian. So you can write:
byte[] bytes = { 0, 0, 0, 25 }; // If the system architecture is little-endian (that is, little end first), // reverse the byte array. if (BitConverter.IsLittleEndian) Array.Reverse(bytes); int i = BitConverter.ToInt32(bytes, 0); Console.WriteLine("int: {0}", i); // Output: int: 25您还应该查看BitConverter.GetBytes(Int32)以将Int32转换为字节数组。 msdn.microsoft/en-us/library/de8fssa4(v=vs.110).aspx [ ^ ]
更多推荐
LSB优先还是MSB优先?
发布评论