 # Convert two characters to one byte

hello,

How can I convert two char variables that have a decimal value in a variable byte?

char v;
byte b1;
char v = SerialUSB.read(); 'v=‘1’ , v=‘A’, v=‘8’ … etc example…
-----------> char v= ‘1’
-----------> char v= ‘A’

b1 = v & v; ---------> b1=0x1A
frame2.data.byte = b1 '= 0x1A= v & v ???

How can I put together two char variables and convert it to a byte variable?

thanks to all

If you are referring to turning ‘1’ ‘A’ into a combined number it is simple binary math. Or in this case Hex math.

You would do it the same way you would do any other math…

the 1 in this case would be 16 * 1 and the A would be 10. So your final 'Decimal" number would be 26.

It takes 2 hex numbers to make 1 Byte since 0xFF = 255 which is the maximum of a Byte.

So you would always multiply the first by 16 and add it to the second.

Below is a very crappy program I quickly wrote recently to turn a list of two character groups into a raw binary. Within that program is the code to do what you want. I’m not saying it is the best way to do it, I’m not saying it’s the fastest way to do it, but it does work.

``````#include <stdio.h>
#include <stdlib.h>

void main(void)
{
FILE *inFile, *outFile;
char buff;
unsigned char outChar;

if (!(inFile = fopen("bms_firmware_2.txt", "r")))
{
printf("\nCOULD NOT OPEN INPUT!\n");
}

if (!(outFile = fopen("bms.bin", "wb")))
{
printf("\nCOULD NOT OPEN OUTPUT FILE!\n");
}

printf("\nStart of program\n");

while (!feof(inFile))
{
fgets(buff, 80, inFile);
printf(".");
if (buff >= '0' && buff <= '9') outChar = (buff - '0') * 16;
else outChar = (buff - 'a' + 10) * 16;
if (buff >= '0' && buff <= '9') outChar += (buff - '0');
else outChar += (buff - 'a' + 10);
fputc(outChar, outFile);
}
fclose(inFile);
fclose(outFile);
}``````

I do not mean to turn into binary. I read a data from the serial port, that data I keep in a char, but that data is already binary v  = ‘1’ v  = 'A’
but in frame2.data.byte  you have to put a hexadecimal byte, as I can put two char and put them in a byte, that is: 0x1A
I feel if I do not explain myself well

No, I’m pretty sure I know what you meant and the code I posted does what you want.

``````      if (buff >= '0' && buff <= '9') outChar = (buff - '0') * 16;
else outChar = (buff - 'a' + 10) * 16;
if (buff >= '0' && buff <= '9') outChar += (buff - '0');
else outChar += (buff - 'a' + 10);``````

That is, it takes two characters with hex codes in them and turns them into one 8 bit hexadecimal number. Perhaps my previous terminology was just not clear about that.

Sorry, my answer was for redheadedrod, but they blocked me and it was posted after your answer. I used it in my project and it works very well! Thank you!

Yes, Sorry about that - for some reason, our forum software wanted your post to be approved before it went on the forum.