tags:

views:

134

answers:

7

I have a lot of #define's in my code. Now a weird problem has crept up.

I have this:

#define _ImmSign    010100

(I'm trying to simulate a binary number)

Obviously, I expect the number to become 10100. But when I use the number it has changed into 4160.

What is happening here? And how do I stop it?

ADDITIONAL

Okay, so this is due to the language interpreting this as an octal. Is there some smart way however to force the language to interpret the numbers as integers? If a leading 0 defines octal, and 0x defines hexadecimal now that I think of it...

+12  A: 

Integer literals starting with a 0 are interpreted as octal, not decimal, in the same way that integer literals starting with 0x are interpreted as hexadecimal.

Remove the leading zero and you should be good to go.

Note also that identifiers beginning with an underscore followed by a capital letter or another underscore are reserved for the implementation, so you shouldn't define them in your code.

James McNellis
quick answer! Is there another way of stopping this then removing the leading zero's?
NomeN
@NomeN: No; that's a fundamental part of the language.
James McNellis
+4  A: 

Prefixing an integer with 0 makes it an octal number instead of decimal, and 010100 in octal is 4160 in decimal.

Maulrus
another quick reply, thx! Is there another way of fixing this in stead of removing the leading 0's?
NomeN
Not that I'm aware of.
Maulrus
+2  A: 

There is no binary number syntax in C, at least without some compiler extension. What you see is 010100 interpreted as an octal (base 8) number: it is done when a numeric literal begins with 0.

doublep
+2  A: 

010100 is treated as octal by C because of the leading 0. Octal 10100 is 4160.

petersohn
+2  A: 

Check this out it has some macros for using binary numbers in C http://www.velocityreviews.com/forums/t318127-using-binary-numbers-in-c.html

There is another thread that has this also http://stackoverflow.com/questions/2611764/can-i-use-a-binary-literal-in-c-or-c

Romain Hippeau
A: 

Octal :-)

You may find these macros helpful to represent binary numbers with decimal or octal numbers in the form of 1's and 0's. They do handle leading zeros, but unfortunately you have to pick the correct macro name depending on whether you have a leading zero or not. Not perfect, but hopefully helpful.

Eric J.
+1  A: 

If you are willing to write non-portable code and use gcc, you can use the binary constants extension:

#define _ImmSign    0b010100
R Samuel Klatchko
argh...I have searched for this one several times but it never came up in google. SO rocks!
NomeN