How can I print out the first and second byte of a member inside a struct?
How can I printf()
out the first & second byte of a member inside a struct in one line?
//example
int aNum=513;
int main(){
printf("\n %02i %02i",((char*)&aNum)[0],((char*)&aNum)[1]); // --> 01 02
}
How can do the same as the above in a member of a struct?
struct test {
int aNum;
};
int main(){
struct test * r;
r->aNum=513;
printf("\n %02i %02i",??,??);
}
Before you can print a member of a structure, you need to have a structure. struct test * r;
does not provide a structure; it provides a pointer to a structure.
You can use struct test s;
to create a structure. If you want to use a pointer to it, you can then use struct test *r = &s;
. Then r->aNum=513;
will store a value in it.
The member of that structure is s.aNum
or r->aNum
. The address of that member is &s.aNum
or &r->aNum
.
You can convert that address of the member to the address of its first byte (same location in memory but a different type in C semantics) with a cast: (unsigned char *) &s.aNum
or (unsigned char *) &r->aNum
. Note that you should generally use unsigned char
rather than char
when working with the bytes that encode objects, to avoid undesired effects in case char
is signed.
Given an address of an unsigned char
, you can access the byte that is 0 or 1 bytes from that address with array subscripting, so ((unsigned char *) &s.aNum)[0]
or ((unsigned char *) &r->aNum)[0]
for the initial byte or ((unsigned char *) &s.aNum)[1]
or ((unsigned char *) &r->aNum)[1]
for the next one.
Your printf
ought to use more than 2
for the field width, since bytes can be more than two decimal digits. (Often when examining raw bytes, we use hexadecimal rather than decimal.)
You can print the two bytes with:
printf("%03i %03i\n", ((unsigned char *) &r->aNum)[0], ((unsigned char *) &r->aNum)[1]);
You should prefer to put the new-line character at the end of a line, not at the beginning. C’s streams are designed for this; a line-buffered stream will send data to the device when a new-line character is encountered. So putting it at the end of a line ensures the line is sent right away. If it is at the beginning, and there is no new-line at the end, then the line may not be sent to the output device until the program does other things.
To print in hexadecimal, use:
printf("%02hhx %02hhx\n", ((unsigned char *) &r->aNum)[0], ((unsigned char *) &r->aNum)[1]);