static_cast

B

Baloff

Hello

//: C03:printBinary.cpp {O}
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt

#include "printBinary.h"
#include <iostream>
void printBinary(const unsigned char val) {
for(int i = 7; i >= 0; i--)
if(val & (1 << i)) //<----this line here ????
std::cout << "1";
else
std::cout << "0";
} ///:~

val is of unsigned char type.
does the bitwise 'and' apply automatic type conversion of the results of
(1 << i)?

thanks
 
K

Kelly Walker

Baloff said:
Hello

//: C03:printBinary.cpp {O}
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt

#include "printBinary.h"
#include <iostream>
void printBinary(const unsigned char val) {
for(int i = 7; i >= 0; i--)
if(val & (1 << i)) //<----this line here ????
std::cout << "1";
else
std::cout << "0";
} ///:~

val is of unsigned char type.
does the bitwise 'and' apply automatic type conversion of the results of
(1 << i)?

thanks

Because the bitwise and operation involves an int and a char, the char (1
byte) is promoted to integer length (probably four bytes). The same thing
happens if you apply other operations to an int and a char (add, subtract,
multiply, etc.). There are promotion rules for all built-in data types that
get applied when two different types are involved in an operation. For
example, ints are promoted to floats, floats to doubles, etc. Any textbook
should cover this sort of thing pretty early on under the heading data type
promotion rules or some such title.

-Kelly
 
V

Victor Bazarov

Baloff said:
//: C03:printBinary.cpp {O}
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt

#include "printBinary.h"
#include <iostream>
void printBinary(const unsigned char val) {
for(int i = 7; i >= 0; i--)
if(val & (1 << i)) //<----this line here ????
std::cout << "1";
else
std::cout << "0";
} ///:~

val is of unsigned char type.
does the bitwise 'and' apply automatic type conversion of the results
of (1 << i)?

Yes. Integral promotions. 'val' is converted to 'int', IIRC.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,142
Messages
2,570,819
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top