小智 49
标准C不定义二进制常量.虽然有一个GNU(我相信)扩展(在流行的编译器中,clang也适应它):0b
前缀:
int foo = 0b1010;
Run Code Online (Sandbox Code Playgroud)
如果你想坚持标准C,那么有一个选项:你可以结合一个宏和一个函数来创建一个几乎可读的"二进制常量"功能:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
int foo = B(1010);
Run Code Online (Sandbox Code Playgroud)
如果你打开繁重的编译器优化,编译器很可能完全消除函数调用(常量折叠)或至少内联它,所以这甚至不会成为性能问题.
证明:
以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
已经编译使用clang -o baz.S baz.c -Wall -O3 -S
,它产生了以下程序集:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
Run Code Online (Sandbox Code Playgroud)
因此clang
完全取消了对函数的调用,并用其替换了它的返回值101
.整洁,对吧?
bas*_*h.d 13
使用0b
像in中的文字前缀
int i = 0b11111111;
Run Code Online (Sandbox Code Playgroud)
看到这里.
使用BOOST_BINARY(是的,您可以在C中使用它).
#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);
Run Code Online (Sandbox Code Playgroud)
在预处理期间,此宏将扩展为八进制文字.