Search code examples
ccharunsigned

Unsigned char to hexstring and back but results don't match


I have an unsigned char array c1 of length 32.

unsigned char c1[32]

Now I have an encryption function, details of which are lengthy.Basically this encryption just puts in some value into c1.

encrypt(&c1,private_key,public_key,message);

Now I have the following code to convert it into hex string:

printf("Initial value is %02x",c1);
char *sit = malloc(sizeof c1 * 2 + 1);
     for (size_t i = 0; i < sizeof c1; i++)
     { sprintf(sit + i * 2, "%02x", c1[i]);
       
     } 

Now I try to get the unsigned char array back:

unsigned char recvalue[32];
     for(int i=0;i<32;i++)
          {
             unsigned testchar=0;
             sscanf(&sit[i*2],"%02x",&testchar);
             recvalue[i]=(unsigned char)testchar;
          }
printf("The final value is %02x",recvalue);

Now the value of c1 and recvalue here does not match but I need them to match. Any help will be appreciated.


Solution

  • %02x (or %02X) format in printf prints at least two digits of the provided integer. It is like a %u, but will print the value given in hexadecimal base instead. However, you're giving it the address of an array. It seems you're confusing it with the %s format, for which you actually give the initial address of a string and it will print the whole string. %02x is different. It requires a integer value. Index the array so you will be giving it actual byte values:

    #include <stdio.h>
    #include <stdint.h>
    #include <stdlib.h>
    
    int main()
    {
        unsigned char c1[32] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                                0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00,
                                0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
                                0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20 };
    
        char *sit = malloc(sizeof c1 * 2 + 1);
        for (size_t i = 0; i < sizeof c1; i++)
        {
            sprintf(sit + i * 2, "%02x", c1[i]);
        }
    
        printf("Initial value is: ");
        for (size_t i = 0; i < sizeof c1; i++)
            printf("%02X ", c1[i]);
        printf("\n");
    
        printf("sit is: %s\n", sit);
    
        unsigned char recvalue[32];
        for(int i=0;i<32;i++)
        {
           unsigned testchar=0;
           sscanf(&sit[i*2],"%02x",&testchar);
           recvalue[i]=(unsigned char)testchar;
        }
    
        printf("The final value is: ");
        for (size_t i = 0; i < sizeof recvalue; i++)
            printf("%02X ", recvalue[i]);
        printf("\n");
    
        return 0;
    }
    

    Output:

    Initial value is: 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20  
    sit is: 0102030405060708090a0b0c0d0e0f001112131415161718191a1b1c1d1e1f20
    The final value is: 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20