By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,113 Members | 1,409 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,113 IT Pros & Developers. It's quick & easy.

static_cast

P: n/a

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

Aug 4 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Baloff" <wa****@wash.edu> wrote in message news:87************@wash.edu...

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
Aug 4 '05 #2

P: n/a
Baloff wrote:
//: 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
Aug 4 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.