Revised answer
You say "I'm making a .COM
executable file so I need to print them as hex bytes". The immediate response is then "Why on earth are you converting the values into a pair of bytes in the first place?" You'll have to convert them back to a single byte and then write that byte using the %c
notation. One way, probably not the best way, to do that is:
static const char hexits[] = "0123456789ABCDEF";
static inline int byte_from_hex(const char *hex)
{
assert(isxdigit(hex[0]) && isxdigit(hex[1]));
int b1 = strchr(hexits, toupper((unsigned char)hex[0])) - hexits;
int b2 = strchr(hexits, toupper((unsigned char)hex[1])) - hexits;
return b1 * 16 + b2;
}
fprintf(w, "%c", byte_from_hex(WRITEME[counter].byte1);
But it would be far simpler not to convert to a string in the first place.
Original answer
Because your data is not null terminated, you need to use a length in the conversion specifications, as specified in the fprintf()
manual page:
%.2s
This means print at most 2 characters from the character array.
fprintf(w, "%.2s", WRITEME[counter].byte1);
This assumes you did something like:
WRITEME[counter].byte1[0] = '0';
WRITEME[counter].byte2[1] = '1';
or:
memmove(WRITEME[counter].byte1, "01", sizeof(WRITEME[counter].byte1);
or (as the comments showed you did):
strncpy(WRITEME[counter].byte1, "01", 2); // or sizeof(WRITEME[counter].byte1)
and that you did not do something like:
sprintf(WRITEME[counter].byte1, "%2X", byte_value);
and that you did not do something like:
strcpy(WRITEME[counter].byte1, "01");