ZeKai ZeKai - 1 year ago 90
C Question

What's this C code means? - Computer Systems A Programmer's Perspective

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]);

void show_int(int x) {
show_bytes((byte_pointer) &x, sizeof(int));

void main() {

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download