probably
char tmp[] = {0x81, 0x00, 0x00, 0x00, 0x12, 0x05};
char new[6];
must be
int tmp[] = {0x81, 0x00, 0x00, 0x00, 0x12, 0x05};
char new[6*2+1];
and
sprintf(tmp + i, "%x", tmp[i]);
must be
sprintf(new + 2*i, "%02x", tmp[i]);
and
for (int i = 0; i < 6; i++) {
printf(" %c", new[i]);
}
must be
for (int i = 0; i < 6*2; i++) {
printf(" %c", new[i]);
}
Execution :
/tmp % ./a.out
81 0 0 0 12 5 8 1 0 0 0 0 0 0 1 2 0 5new: 810000001205
Under valgrind :
/tmp % valgrind ./a.out
==15557== Memcheck, a memory error detector
==15557== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==15557== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==15557== Command: ./a.out
==15557==
81 0 0 0 12 5 8 1 0 0 0 0 0 0 1 2 0 5new: 810000001205
==15557==
==15557== HEAP SUMMARY:
==15557== in use at exit: 0 bytes in 0 blocks
==15557== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==15557==
==15557== All heap blocks were freed -- no leaks are possible
==15557==
==15557== For counts of detected and suppressed errors, rerun with: -v
==15557== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)
sprintf(tmp + i, "%x", tmp[i]);will lead to undefined behavior. You attempt to write a multi-character string into a single character. Not to mention that usingtmp[i]as both an argument and as destination is also UB as per the C specification.new[i]. Also note that ifcharis signed (it may be signed or unsigned, it's an implementation (compiler) detail) then0x81would lead to sign extension as it's considered a negative value. Useuint8_tfrom<stdint.h>for generic unsigned bytes. And please learn about two's complement (which is the most common way to handle negative values).