"Bitwise" 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 is going on here? Why does it x & 070compute a value xbut x & 70compute 0?

My assumption is that an extra 0 on the left forces 60 to take 2 bytes instead of 1. In this case it will not be bitwise and will be as follows:

0000 0000 0001 0000     '16
0000 0000 0100 0110 &   '70
-------------------
0000 0000 0000 0000
+5
source share
4 answers

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

.

+12

, 0 , ( 8). , 70, 56:

0000 0000 0001 0000     '16 
0000 0000 0011 1000 &   '56
------------------- 
0000 0000 0001 0000 
+7

070 0, , , . , 70.

+3

, 070 ( 0x70 ) , .

, , inline:

inline int Foo(int x) { return (x - '!' & 070); }

C ++ did a lot to allow us to get rid of the preprocessor for many things, because it is bad, wrong and dangerous. If you can do without it, do it.
(And if you use it, at least have mercy on those who have to deal with your code later to make macros all-uppercase.)

+3
source

All Articles