Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to convert a decimal number in hexadecimal number and send through serial port with LSB first.

I tried this

C#
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);


Is testBytes[0] contains bytes in LSB first or MSB first???
Posted

Strictly speaking, it depends on the requirements of the device connected to the other end of your RS-232 cable. Windows uses "little-endian" formats (least significant byte goes first); I would say, most systems do the same. However, this is not a rule; "big-endian" is also used. For example, so-called standard "network order" is big-endian.

Please see: http://en.wikipedia.org/wiki/Endianness[^].

—SA
 
Share this answer
 
v3
Comments
DoingWork 25-Mar-14 1:58am    
Thanks for reply.
I want to know only that to send LSB first, Whether I should send testBytes[0] first or testBytes[3] first ?????
Sergey Alexandrovich Kryukov 25-Mar-14 2:56am    
Didn't I just answer? Look at what the other device require and do it.
—SA
This is the way to test taken from msdn: http://msdn.microsoft.com/en-us/library/bb384066.aspx[^]

C#
byte[] bytes = { 0, 0, 0, 25 };

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);

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:
C#
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

You should also look at BitConverter.GetBytes(Int32) for converting Int32 to byte array.
http://msdn.microsoft.com/en-us/library/de8fssa4(v=vs.110).aspx[^]
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900