#include /* putc() */ #include /* CHAR_BIT, INT_MAX, LONG_MIN */ #define PutC(c) (putc( (char) (c), stdout )) #define PutD(d) (PutC( (char) ((d)<10)?('0'+(d)):('A'+(d)-10) )) /* LABELS FOR BITS IN THE 'HOW' MASK */ #define IR_BIT_BASE (0x01) #define IR_BIT_PACK (0x02) #define IR_BIT_ORDER (0x04) /* SYMBOLIC CONSTANTS FOR EACH 'HOW' MODE */ #define IR_BIN (0x00) #define IR_HEX (IR_BIT_BASE) #define IR_PACKED (0x00) #define IR_SPACED (IR_BIT_PACK) #define IR_FWD (0x00) #define IR_REV (IR_BIT_ORDER) /* TO USE: ADD or BITWISE-OR TOGETHER. EG: */ /* FOR REVERSED, SPACED, BIN: how = IR_REV + IR_SPACED + IR_BIN */ /* ALTERNATE WAY: how = IR_REV | IR_SPACED | IR_BIN */ /* The format chosen for this demo */ #define FORMAT ( IR_FWD | IR_SPACED | IR_BIN ) int PutIR(void *base, size_t size, int how) { unsigned char *ptr, *start; unsigned char mask; int i, nibble, step, chars; /* Set up based on byte order */ start = (unsigned char *) base + ((how & IR_BIT_ORDER)? (size-1) : 0); step = (how & IR_BIT_ORDER)? -1: 1; /* Process bytes one at a time */ for (i = 0, chars = 0, ptr = start; i < size; ptr += step, i++) { /* Inter-byte space if requested */ if ( (how & IR_BIT_PACK) && (ptr != start) ) { PutC(' '); chars++; } /* Print out the byte */ if (how & IR_BIT_BASE) for (nibble = (CHAR_BIT - 1)/4; nibble >= 0; nibble--) { PutD( ( (0x0F << 4*nibble) & (*ptr)) >> 4*nibble ); chars++; } else for (mask = 1 << (CHAR_BIT - 1); mask; mask >>= 1) { PutD( (mask & *ptr)? 1 : 0 ); chars++; } } return chars; } int main(void) { int junk; long junk_l; junk = INT_MAX; PutIR(&junk, sizeof(junk), FORMAT); PutC('\n'); junk_l = LONG_MIN; PutIR(&junk_l, sizeof(junk_l), FORMAT); return 0; }