本文介绍了LSB优先还是MSB优先?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用十六进制数转换一个十进制数,然后先用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???
推荐答案
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转换为字节数组。
[]
这篇关于LSB优先还是MSB优先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!