/**************************************************************************** *** FILE: bits.cpp *** DATE: Nov 15, 2003 *** AUTHOR: Daniel Dementiev *** DESCR: This is a short example for Algorithms class. This program *** illustrates two ways of getting a bit representation of a number. *** The first is "traditional" - by dividing number by two *** and the other one by using the UNION construct and specifying *** the size of structure elements in bits; ****************************************************************************/ #include #include using namespace std; typedef unsigned char byte; typedef unsigned short int shword; // ---------------------- // This special structure allows us to access aither a whole // byte value (byte_value) or each bit inside that byte. // The nested structure "bits" contains 8 elements (b0-b7) // size of exactly one bit each. // The "union" construction stores both the byte value "byte" // and structure "bits" in the same memory cell. // Thus, a value of a variable of the ByteBitMap type can be // accessed as either: // - var.byte_value // or as // - var.bits // ---------------------- union ByteBitMap { byte byte_value; struct { shword b0:1; shword b1:1; shword b2:1; shword b3:1; shword b4:1; shword b5:1; shword b6:1; shword b7:1; } bits; }; void print_bits(byte value) { ByteBitMap b; b.byte_value = value; cout<(b.byte_value)<<" = "; cout<>= 1; } return res; } // ---------------------------------- union IntByteMap { unsigned int int_value; struct { byte b0; byte b1; byte b2; byte b3; } bytes; }; void print_bytes(unsigned int n) { IntByteMap m; m.int_value = n; cout<(m.bytes.b3)<<"." <(m.bytes.b2)<<"." <(m.bytes.b1)<<"." <(m.bytes.b0)<>n; b = n; cout<(b)<<" = "<>n; print_bytes(n); }