Search code examples
chexasciiposixconverters

Converting char holding hex(1byte) to 2 char string


I am dealing with some image recognition program. I read all data to a char buffer. The image contains hex data so I read byte by byte to my buffer and I'm dealing with them later on.

My problem is: how to convert and get data from a char(1 byte) that contains read hex data and make it 2 sized char arrays?

Example: 8c -> read into character contains -116. I cant seem to find any way to make it char array[0] ='8' and array[1]='c'

 if(buffer[4] < 10 && buffer[4] >= 0) {
            buyut1[0] = '0';
            buyut1[1] = buffer[4];
            sprintf(offSet, "%s", buyut1);
        }
        else{
            sprintf(offSet, "%x", buffer[4]);
        }
        if(buffer[5] < 10 && buffer[5] >= 0) {
            buyut2[0] = '0';
            buyut2[1] = buffer[5];
            sprintf(offSet,"%s""%c""%x",offSet,'0',buffer[5]);

        }
        else{
            sprintf(offSet,"%s%x",offSet,buffer[5]);
        }

I can convert something that is like 6c which contains a positive number in a signed form I think. Or something like 03 which begins with a 0.

But 8c, for example, has -116 and is not working with my function.


Solution

  • Specify to the sprintf() function that you want output of hexa value of two characters, and cast input buffer[4] to unsigned char:

    sprintf( offSet, "%02x", (unsigned char)buffer[4]);