I'm trying to write a Dec to Hex function that would return the Decimal value (up to 697, 0x255) as 2 bytes (uint8_t) so that I can write those values from a byte array.
int Dec2Hex(int DecimalVal, uint8_t &MSB, uint8_t &LSB) {
//Convert a Decimal Number (DecimalVal) to Hex
char HexChars[12] = {0};
sprintf(HexChars, "0x%02X", DecimalVal);
Two Questions:
How do I access more than 1 character of the HexChars array (other than substring with a String) for the LSB byte (the MSB will only be a 0, 1 or 2)?
How do I convert the value to a HEX Byte?
I tried strtol, but I couldn't figure it out to get it to work.
I can break the char array into 2 strings, but I can't for the life of me, figure out how to return values such as "A".
I have been digging around for a function, that would do this, but I'm still stumped!
Sorry, but I'm confused about what you're trying to do... I think I'm confused by "byte array".
Everything "inside" the computer is binary. For example 01010101 can be displayed as 55 hex but by default you'll see 85 decimal. That's assuming it's a value/variable, not an ASCII representation of a value.
Or we could have 0101 0101 0101 0101 which is 2 bytes (spaces added for human readability) and 5555 hex or 21,845 decimal.
That's a regular 16-bit integer but you can split it into two bytes with "bit manipulation", masking the high-byte to leave the just the low-byte value, and by bit-shifting right by 8-bits to leave the just high-byte. You can write those two values into separate byte variables (both equal to 55 hex or 85 decimal in the above example).
WOW, that Works for me!
Just to recap, I'm writing code to write to the communications on an ICOM radio, which is all in HEX, via the communications (I'm using Bluetooth).
The receive string looks like:
<FE FE E0 A4 14 0A 02 55 FD>
There are 2 start bytes (FE FE), From Address (EO), To Address (A0), Command (14), the data (02, 55) and StopByte (FD).
I'm trying to construct the data array (bytes) to set the RF output power to the radio.
Your solution solves my problem, quite simply!!!
Both names are incorrect and meaningless in this application. You're simply separating the MSB and LSB of a 16-bit (unsigned) integer into two variables to transfer over a byte-oriented interface. Nothing is being converted. Countless newbies get wrapped around the axle over Hex, Decimal, etc. As mentioned above, these are merely human-readable presentations of binary values.