写二进制数字系统用C code [英] Writing binary number system in C code
问题描述
由于我们使用 0X
preFIX为十六进制数字,而 0
八进制的人,有什么可以为二进制数做些什么呢?
As we use 0x
prefix for hex numbers, and o
for octal ones, is there anything that can be done for binary numbers?
我试过 B
后缀,但 GCC 没'T允许它。
I tried the b
suffix, but the GCC didn't allow it.
错误:整型常量无效标b
Error: invalid suffix "b" on integer constant
这可能吗?
推荐答案
标准C没有定义二进制常量。有一个GNU(我相信)扩展,但(流行的编译器中,铛适应它):在 0B
preFIX:
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
如果你想坚持使用标准的C,然后有一个选项:你可以结合宏和一个函数来创建的几乎的可读二进制常数功能:
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#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;
}
然后你可以使用它是这样的:
And then you can use it like this:
int foo = B(1010);
如果您打开沉重的编译器优化,编译器将最有可能完全(常量折叠)消除函数调用,或至少会内联,所以这不会甚至性能问题。
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
证明:
以下code:
#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;
}
使用铛-o baz.S baz.c -Wall -O3 -S
已编制,并产生了以下组件:
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.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
所以铛
完全消除了通话的功能,并与取代它的返回值101
。整洁的,是吧?
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
这篇关于写二进制数字系统用C code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!