Convert two characters to one byte


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

char v[50];
byte b1;
char v[50] =; 'v[0]=‘1’ , v[1]=‘A’, v[2]=‘8’ … etc example…
-----------> char v[0]= ‘1’
-----------> char v[1]= ‘A’

b1 = v[0] & v[1]; ---------> b1=0x1A[0] = b1 '= 0x1A= v[0] & v[1] ???

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[80];
   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);
      if (buff[0] >= '0' && buff[0] <= '9') outChar = (buff[0] - '0') * 16;
      else outChar = (buff[0] - 'a' + 10) * 16;
      if (buff[1] >= '0' && buff[1] <= '9') outChar += (buff[1] - '0');
      else outChar += (buff[1] - 'a' + 10);
      fputc(outChar, 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 [0] = ‘1’ v [1] = 'A’
but in [0] 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] >= '0' && buff[0] <= '9') outChar = (buff[0] - '0') * 16;
      else outChar = (buff[0] - 'a' + 10) * 16;
      if (buff[1] >= '0' && buff[1] <= '9') outChar += (buff[1] - '0');
      else outChar += (buff[1] - '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.