-1

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.

  • when writing a string in C, `"%s""%s"` just means a string `"%s"` followed by a string `"%s"`, which will be concatenated by the compiler to `%s%"`. Use `"\"%s\""` to put quotes inside a string. – Paul Ogilvie Mar 17 '18 at 09:41
  • 1
    Possible duplicate of [How do you convert a byte array to a hexadecimal string in C?](https://stackoverflow.com/questions/6357031/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-in-c). Or [this](https://stackoverflow.com/q/4085612/69809), or [this](https://stackoverflow.com/q/25341676/69809). – vgru Mar 17 '18 at 09:42
  • If `buffer` already contains the hex representation of the data, i.e. `buffer[4]` is `'8'`, then the value of this byte is between `'0'` and `'9'`, not `0` and `9`. Which means you simply need to print `buffer` directly. The statement *"char(1 byte) contains read hex data"* doesn't make sense - either it contains bytes, or it already contains the hexadecimal representation of the data in ascii form. There is no such thing as "hex data". – vgru Mar 17 '18 at 09:49
  • I dont need to print buffer or something . I need 8c as 8 and c seperetely so i can manipulate data – itsfreeandtakesminute Mar 17 '18 at 09:56
  • @Groo buffer contains 8c as char which shows -116 i need something to make it 8 in array(0) c in array(1) – itsfreeandtakesminute Mar 17 '18 at 10:05
  • So `buffer[5]` contains the character `c`? And you want `array[1]` to hold that same character? – vgru Mar 17 '18 at 10:15
  • buffer 5 is irreleveant buffer(4) contains 8c itself – itsfreeandtakesminute Mar 17 '18 at 11:47

1 Answers1

0

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]);
John Smith
  • 96
  • 3