# Decimal to Hex nibbles conversion for UART communicaiton

Hi All!

I am pretty novice in Arduino, but understand most programming concepts and have worked mostly in Python and VBA. I am struggling in the Arduino IDE and need some help. I am trying to send and receive serial information using UART protocal to a motor control board to control RPM.

What I need:
-I need to convert multi-digit Decimal to Hex nibbles. For example 802466 --> 0X02 0XA 0XE 0X03 0XC 0X00 0X00
-- have found several different ways to convert Decimal to hex, but none that breaks it into nibbles
-I also need to convert it back to Decimal form.

If I can do that I think I can figure everything else out, but if you know any tricks or shortcuts to simplify defining the UART protocol in Arduino that would be much appreciated!

Thank you!

Hint: your computer knows only binary.

(Is endianness important?)

So basically you want to convert a unsigned integer (or long) to HEX, represented in characters ? For what ? i have to ask, because if you just want to convert it back at the other end there is no need.
Well i can think of 2 ways, but since one involves the use of 'String' i will focus on the other method.
One more thing would be .. do you need the leading zeroes , let's assume you do.

``````uint32_t value = 802466UL;
char outstr;
uint8_t i = 7;
while (i) {
uint8_t temp = value & 0xF;
value = value >> 4;
temp = temp + ' 0';
if (temp > '9') temp = temp - '0' + 'A' - 10;  // i think !?
outstr[i] = (char) temp;
i--;
}
``````

This should result in the hexadecimal representation.
There is of course the very simple `String(value, HEX);`
but that will not print any leading zeroes, so you would have to add them manually if you want them.

Something like this ? fI91Np - Online C++ Compiler & Debugging Tool - Ideone.com

1. Given:

``````unsigned long y = 802466;  //'8', '0', '2', '4', '6', '6' or C3EA2 --> 'C', '3', 'E', 'A', '2'
``````

2. You can nicely send the ASCII codes for --
(1) the decimal digits of the decimal number ('8', '0', '2', '4', '6', '6') or
(2) the corresponding hex digits of the decimal number (802466=0xC3EA2-->'C', '3', 'E', 'A', '2')

3. Snippet Codes to send decimal digits of the decimal number ('8', '0', '2', '4', '6', '6') over UART

``````unsigned long y = 802466; //8, 0, 2, 4, 6, 6
byte decDigit;

do
{
decDigit[i] = y%10;
y = y/10;
i++;
}
while(y != 0);  //decDigit[] = {6, 6, 4 2, 0, 8};

for(int j=0; j<i; j++)
{

Serial.write(decDigit[j] + 0x30); //goes to receiver: 0x36, 0x36, 0x34, 0x32, 0x30, 0x38
}
``````

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.