[英]Printing a long in binary 64-bit representation
I'm trying to print the binary representation of a long in order to practice bit manipulation and setting various bits in the long for a project I am working on. 我正在尝试打印long的二进制表示形式,以便练习位操作并为我正在研究的项目在long中设置各种位。 I successfully can print the bits on ints but whenever I try to print 64 bits of a long the output is screwy.
我可以成功打印int上的位,但是每当我尝试打印64位长的输出时,输出都是错误的。 Here is my code:
这是我的代码:
#include <stdio.h>
void printbits(unsigned long n){
unsigned long i;
i = 1<<(sizeof(n)*4-1);
while(i>0){
if(n&1)
printf("1");
else
printf("0");
i >>= 1;
}
int main(){
unsigned long n=10;
printbits(n);
printf("\n");
}
My output is 0000000000000000000000000000111111111111111111111111111111111110. Thanks for help! 我的输出是0000000000000000000000000000111111111111111111111111111111111110.谢谢!
unsigned long
, 1 << …
is an int
, so you need 1UL
unsigned long
, 1 << …
还是一个int
,因此您需要1UL
n&1
should be n&i
n&1
应该是n&i
Fixes only: 仅修复:
#include <limits.h>
#include <stdio.h>
void printbits(unsigned long n){
unsigned long i;
i = 1UL<<(sizeof(n)*CHAR_BIT-1);
while(i>0){
if(n&i)
printf("1");
else
printf("0");
i >>= 1;
}
}
int main(){
unsigned long n=10;
printbits(n);
printf("\n");
}
And if you want to print a 64-bit number specifically, I would hard-code 64 and use uint_least64_t
. 而且,如果您要专门打印一个64位数字,我将对64进行硬编码并使用
uint_least64_t
。
The problem is that i = 1<<(sizeof(n)*4-1)
is not correct for a number of reasons. 问题是,由于多种原因,
i = 1<<(sizeof(n)*4-1)
不正确。
sizeof(n)*4
is 32, not 64. you probably want sizeof(n)*8
sizeof(n)*4
是32,而不是64。您可能想要sizeof(n)*8
1<<63
may give you overflow because 1 may be 32-bits by default. 1<<63
可能会给您带来溢出,因为默认情况下1可能是32位。 You should use 1ULL<<(sizeof(n)*8-1)
1ULL<<(sizeof(n)*8-1)
unsigned long
is not necessarily 64 bits. unsigned long
不一定是64位。 You should use unsigned long long
unsigned long long
If you want to be extra thorough, use sizeof(n) * CHAR_BIT
(defined in <limits.h>
). 如果要更彻底,请使用
sizeof(n) * CHAR_BIT
(在<limits.h>
定义)。
In general, you should use stdint
defines (eg uint64_t
) whenever possible. 通常,应尽可能使用
stdint
定义(例如uint64_t
)。
The following should do what you want: 以下应该做您想要的:
#include <stdio.h>
void printbits(unsigned long number, unsigned int num_bits_to_print)
{
if (number || num_bits_to_print > 0) {
printbits(number >> 1, num_bits_to_print - 1);
printf("%d", number & 1);
}
}
We keep calling the function recursively until either we've printed enough bits, or we've printed the whole number, whichever takes more bits. 我们一直递归地调用该函数,直到我们打印了足够的位,或者我们打印了整数(以占用更多位为准)为止。
wrapping this in another function directly does exactly what you want: 将其直接包装到另一个函数中可以完全满足您的要求:
void printbits64(unsigned long number) {
printbits(number, 64);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.