I'm trying to do this :

uint64_t key = 0110000010110110011001101111101000111111111010001011000110001110;

Doesn't work. GCC says

warning: integer constant is too large for its type

Any idea why?

有帮助吗?

解决方案

Although neither the draft C99 standard nor the draft C11 standard support binary literals, since you specifically mention gcc it has an extension for binary literals which says:

Integer constants can be written as binary constants, consisting of a sequence of ‘0’ and ‘1’ digits, prefixed by ‘0b’ or ‘0B’. This is particularly useful in environments that operate a lot on the bit level (like microcontrollers).

they gives the following example (see it live):

i = 0b101010;

and it looks like clang also support this as an extension as well (see it live):

[...]binary literals (for instance, 0b10010) are recognized. Clang supports this feature as an extension in all language modes.

This is not available in standard C++ either until C++14 [lex.icon].

其他提示

Due to the leading 0 that's read as a very large octal literal, which is probably not what you want. Amazingly, C doesn't have binary literals.

As an extension, gcc supports binary literals with the 0b prefix, eg, 0b101010. If you don't want to rely on extensions, hexadecimal is probably the most reasonable alternative.

Use Hex decimal they are more compact and can represent binary example:

0x01 // This is 0001
0x02 // 0010

Using binary the way you want is particularly ugly inside someone's code.

Also starting a number with 0 (in your example) will be interpreted as octal.

To add to @Shafik's answer:

#include <inttypes.h>
#include <stdio.h>

int main(void)
{
    uint64_t i = UINT64_C(
        0b0110000010110110011001101111101000111111111010001011000110001110);

    printf("%" PRIX64 "\n", i) ;
    return 0;
}

Worked with: gcc -std=gnu99 - output: 60B666FA3FE8B18E

Really, embedded systems are much more strict about extensions, particularly if you're unfortunate enough to be required to adhere to standards like MISRA-C. Hexadecimal conversion is just the grouping of 4 binary digits to 0x0 -> 0xf.

I think that is because you exceeded the maximum integer that can be stored in an uint datatype. Try using an array of boolean type.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top