在C中将整数转换为32位二进制 [英] convert integer to 32-bit binary in c

查看:423
本文介绍了在C中将整数转换为32位二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,将整数转换为32位二进制数.问题出在输出上-它倒退了.

I'm writing a program to convert an integer to 32-bit binary. The problem is with the output - it comes backwards.

#include <stdio.h>

int main() {
    long number, binary, num2;

    printf("Enter an integer: ");
    scanf("%ld", &number);

    for (num2 = (number * 2) / 2; num2 > 0; num2 /= 2) {
        binary = num2 % 2;
        printf("%ld", binary);
    }
    putchar('\n');
    return 0;
}

因此,如果我输入"6",则显示为011,必须为110

So if I put '6' it shows as 011 and it has to be 110

此外,我如何输出其余的'0'?这样,在这种情况下,整个输出将是:

Also, how do I output the rest of '0's? So that the whole output in this case would be:

00000000 00000000 00000000 00000110 

推荐答案

您从右边开始计算数字,这就是为什么您的输出首先显示最右边的数字的原因.这是一种从左开始使用位掩码的方法,并且不会将您的值转换为无符号的值,这可能会更改位:

You compute digits starting from the right, which is why your output shows the right-most digit first. Here is a way that starts from the left, using a bitmask, and does not convert your value to unsigned which may change the bits:

#include <stdio.h>
#include <limits.h>

int main()
{
    long number;
    if ( 1 != scanf("%ld", &number) )
        return 1;

    // sign bit  (cannot use 1L left-shift as that causes UB)
    putchar( '0' + (number < 0) );

    // value bits
    for (long bit = 1L << (CHAR_BIT * sizeof number - 2); bit; bit >>= 1)
        putchar( '0' + !!(number & bit) );

    putchar('\n');
}

这篇关于在C中将整数转换为32位二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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