Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Bitwise And" and Left-Padding in C++

I have a macro that looks something like this:

Foo(x) ((x - '!') & 070)

If I call the following code:

Foo('1') => 16

However, if I call the following code:

(('1' - '!') & 70) => 0

So my question is, what's going on here? Why does x & 070 compute to x but x & 70 compute to 0?

My guess is that the extra 0 on the left is forcing 60 to take 2 bytes instead of 1. In that case, wouldn't the bitwise & be as follows?

0000 0000 0001 0000     '16
0000 0000 0100 0110 &   '70
-------------------
0000 0000 0000 0000
like image 720
sohum Avatar asked Jul 01 '10 18:07

sohum


2 Answers

In C++, a constant with a leading 0 is an octal constant, not a decimal constant. It is still an integer constant but 070 == 56.

This is the cause of the difference in behaviour.

like image 126
CB Bailey Avatar answered Oct 22 '22 14:10

CB Bailey


No, the extra 0 means the number is read as octal (base 8). That means it doesn't say 70, but 56:

0000 0000 0001 0000     '16 
0000 0000 0011 1000 &   '56
------------------- 
0000 0000 0001 0000 
like image 25
Michael Madsen Avatar answered Oct 22 '22 14:10

Michael Madsen