The value C determines changes unexpectedly.

There is a lot of #define in my code. Now a strange problem has arisen.

I have it:

 #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 changes to 4160.

What's going on here? And how to stop it?

ADDITIONAL

Well, this is because the language interprets it as octal. Is there any smart way to make the language interpret numbers as integers? If leading 0 defines an octal and 0x defines a hexadecimal number now when I think about it ...

+6
c c-preprocessor
source share
7 answers

If you want to write non-portable code and use gcc, you can use the binary const extension :

 #define _ImmSign 0b010100 
+1
source share

Integer literals starting with 0 are interpreted as octal rather than decimal, just as integer literals starting with 0x are interpreted as hexadecimal.

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

Note that identifiers starting with an underscore followed by a capital letter or other underscore are reserved for implementation, so you should not define them in your code.

+13
source share

The prefix of an integer with 0 makes it an octal number instead of decimal, and 010100 in octal - 4160 in decimal format.

+4
source share

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

+2
source share

010100 is treated as the octal value of C due to the leading 0. Octal 10100 is 4160.

+2
source share

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. Can I use a binary literal in C or C ++?

+2
source share

Octal :-)

You may find these macros useful for representing binary numbers with decimal or octal numbers in the form 1 and 0. They process leading zeros, but unfortunately you need to choose the correct macro name depending on whether you have a leading zero or not . Not perfect, but hopefully useful.

0
source share

All Articles