Reputation:
I would like to know the function show_int() below actually do...
This code is in the page 28 of Computer Systems A Programmer's Perspective.
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int len) {
int i;
for (i = 0; i < len; i++) {
printf("%.2x", start[i]);
}
printf("\n");
}
void show_int(int x) {
show_bytes((byte_pointer) &x, sizeof(int));
}
void main() {
show_int(20);
getchar();
}
Upvotes: 1
Views: 312
Reputation: 24344
The most important thing to understand is the cast to *byte_pointer
(a.k.a. unsigned char
):
(byte_pointer) &x
You may think of it as converting pointer to int
(in your case: 20) to a series of bytes (that can be 4 or 8 or even more bytes, depending on the architecture).
What the show_bytes()
function is then doing is just iterating over a byte array to show its subsequent bytes, formatting it to hexadecimal format.
Upvotes: 1