Printing binary in binary format

Bruce Eckel’s Thinking in C ++ has a program for printing double values
in binary format. (Chapter 3, p. 189)

int main(int argc, char* argv[]) { if(argc != 2) { cout << "Must provide a number" << endl; exit(1); } double d = atof(argv[1]); unsigned char* cp = reinterpret_cast<unsigned char*>(&d); for(int i = sizeof(double); i > 0 ; i -= 2) { printBinary(cp[i-1]); printBinary(cp[i]); } } 

Here when printing cp [i], when i = 8 (assuming double has 8 bytes), would this behavior be undefined?
I mean that this code does not work, since it does not print cp [0].

+4
source share
3 answers

A1: Yes, this will be undefined behavior when accessing cp [8].

A2: Yes, it also does not print cp [0].

As shown, it prints bytes 7, 8, 5, 6, 3, 4, 2, 1 of valid values ​​0..7. So, if you correctly copied the code from the book, there is an error in the code of the book. Check the error page for the book, if there is one.

It is also strange that he unwinds the cycle; simpler wording:

 for (int i = sizeof(double); i-- > 0; ) printBinary(cp[i]); 

There is also, apparently, a good reason for printing bytes in reverse order; it’s not obvious what it will be.

+4
source

It looks like a typo in the book code. The second call should be printBinary(cp[i-2]) .

This is a little strange because they change the byte order compared to what is actually in memory (IEEE 754 floating-point numbers do not have content-ability rules, so I think it really is on its platform), and because it counts at 2 instead of 1.

It would be easier to write

 for(int i = 0; i != sizeof(double) ; ++i) printBinary(cp[i]); 

or (if it's important to reverse bytes) use the standard idiom for a loop that counts

 for(int i = sizeof(double); (i--) > 0;) printBinary(cp[i]); 
+2
source

You can do this in a way that is independent of you by running double in an unsigned long long. You can then use a simple integer bit offset to access and print bits, from bits 0 to bits 63.

(I wrote a C function called print_raw_double_binary () that does this - see my article Displaying the Source Fields of a Floating Point Number for more details.)

0
source

Source: https://habr.com/ru/post/1308608/


All Articles