C印花位 [英] C printing bits

查看:116
本文介绍了C印花位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C编写一个程序,打印的int位。
由于某种原因,我得到错误的价值观,

I am trying to write a program in C that prints bits of int. for some reason i get wrong values,

void printBits(unsigned int num){
    unsigned int size = sizeof(unsigned int);
    unsigned int maxPow = 1<<(size*8-1);
    printf("MAX POW : %u\n",maxPow);
    int i=0,j;
    for(;i<size;++i){
        for(j=0;j<8;++j){
            // print last bit and shift left.
            printf("%u ",num&maxPow);
            num = num<<1;
        }
    }
}

我的问题,第一为什么会出现这种结果(printBits(3))。

My question, first why am i getting this result (for printBits(3)).

MAX POW:2147483648 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

  0 0 0 0 0 2147483648 214748364 8

MAX POW : 2147483648 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 2147483648 214748364 8

第二有没有更好的方式来做到这一点?

second is there a better way to do this ?

推荐答案

您是否正确计算的结果,但你不是的打印的是正确的。同时你并不需要第二个循环:

You are calculating the result correctly, but you are not printing it right. Also you do not need a second loop:

for(;i<size*8;++i){
    // print last bit and shift left.
    printf("%u ",num&maxPow ? 1 : 0);
    num = num<<1;
}

如果你想炫耀,你可以用两个惊叹号代替有条件的:

If you'd like to show off, you could replace the conditional with two exclamation points:

printf("%u ", !!(num&maxPow));

这篇关于C印花位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆