Convert int16 to byte array
I'm really new to C, and so a bit confused.
I am trying to convert an int16 to a byte[] array.
I have a int16 like -200, and I want to convert it into a byte[2] array, like the following example does.
Velocity = -200 = hex FF38 = [hex FF] [hex 38] = [255] [56]
I am taking the values and passing them to the serial port like below, but I need to pass the int16, and have a function convert it to the byte[] for me.
Serial.print(255,BYTE);
Serial.print(56,BYTE);
I found the following code, but couldn't get it to work
Serial.print((velocity & 0xff00) >> 8, BYTE);
Serial.print(velocity & 0xff, BYTE);
开发者_JS百科Any suggestions?? Any help would be appreciated.
Your approach looks fine, but maybe you're getting tripped up by an endianness issue?
Serial protocols may also be regarded as either little or big-endian at the bit- and/or byte-levels (which may differ). Many serial interfaces, such as the ubiquitous USB, are little-endian at the bit-level. Physical standards like RS-232, RS-422 and RS-485 are also typically used with UARTs that send the least significant bit first...
Your code sends the most significant byte first ("big-endian").
精彩评论