Answer to Question 2.6
/* Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
/* The C++ Answer Book */
/* Tony Hansen */
/* All rights reserved. */
//: print the bits of a null character pointer
#include <stream.h>
#include <limits.h>
#include "2_6a.c" /* EXPAND */
#include "2_6c.c" /* EXPAND */
void prbits(char byte)
{
cout << "0b";
for (unsigned long mask = HIBIT(unsigned char);
mask != 0; mask >>= 1)
if ((byte & mask) != 0)
cout << "1";
else
cout << "0";
}
int main(int, char**)
{
#include "2_6b.c" /* EXPAND4 */
for (int i = 0; i < sizeof(char*); i++)
{
cout << "byte " << i << " = ";
prbits(pi.byte[i]);
cout << "\n";
}
return 0;
}
//:2_6a.c
union ptr_bits
{
char *ptr;
char byte[sizeof(char*)];
};
//:2_6c.c
#undef BITS /* DELETE */
#define BITS(type) (CHAR_BIT * (int)sizeof(type))
#define HIBIT(type) ((type)(((type) 1) << \
(BITS(type) - 1)))
Menu of Chapter 2 Answers
Answer to Question 2.7