Reputation: 23
I need to print bytes in hexadecimal
form in C
. All I’ve managed to do is to print 1 byte at a time, where my program has to support the option for 1, 2 or 4 bytes (size parameter).
this is my function:
void memDisaply(char* filename, int size) {
char sentence [100];
unsigned int str[20];
int length,i;
unsigned char* ptr;
printf("Please enter <address> <length>\n");
fflush(stdin);
fgets(sentence,100,stdin);
fgets(sentence,100,stdin);
sscanf (sentence,"%x %d",str,&length);
ptr = (unsigned char*)str;
for (i=0 ; i< length ; i++) {
printf ("%02x",(unsigned int)ptr[i]);
}
/*reset values*/
length = 0;
i = 0;
ptr = NULL;
}
the output is as follows (where size=1, and length= 10):
31 ED 5E 89 E1 83 E4 F0 50 54
I need that when size = 2
and length = 5
that the output will be:
ED31 895E 83E1 F0E4 5450
(notice the little endian
)
I somehow need to use the size argument to alter the output but I don't know how.
I assume it got something to do with the %02x
format, and I've tried %04x
but all I got was:
0031 00ED 005E 0089 00E1 0083 00E4 00F0 0050 0054
Upvotes: 2
Views: 21543
Reputation: 145849
Read two bytes by two bytes and do:
printf ("%04x", (unsigned int) ptr[i] | (unsigned int) ptr[i + 1] << 8);
Upvotes: 2