使用C的Long Long十进制二进制表示形式 [英] Long Long Decimal Binary Representation using C

查看:513
本文介绍了使用C的Long Long十进制二进制表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 C编程

我的代码是

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

int main()
{
    long long number, binaryRepresentation = 0, baseOfOne = 1, remainder;
    scanf("%lld", &number);
    while(number > 0) {
        remainder = number % 2;
        binaryRepresentation = binaryRepresentation + remainder * baseOfOne;
        baseOfOne *= 10;
        number = number / 2;
    }
    printf("%lld\n", binaryRepresentation);

}

当我输入 5 时,上面的代码可以正常工作,而当数字为 9223372036854775807(0x7FFFFFFFFFFFFFFF)时,上述代码将失败.

The above code works fine when I provide an input of 5 and fails when the number is 9223372036854775807 (0x7FFFFFFFFFFFFFFF).

1.测试用例

5
101

2.测试用例

9223372036854775807
-1024819115206086201

推荐答案

使用一个拒绝数表示二进制数字永远不会特别好:输入极少的输入,您将很容易溢出,所有后续的算术运算都将是毫无意义.

Using a denary number to represent binary digits never ends particularly well: you'll be vulnerable to overflow for a surprisingly small input, and all subsequent arithmetic operations will be meaningless.

另一种方法是随手打印数字,但使用递归技术,因此您可以按与处理数字相反的顺序打印数字:

Another approach is to print the numbers out as you go, but using a recursive technique so you print the numbers in the reverse order to which they are processed:

#include <stdio.h>

unsigned long long output(unsigned long long n)
{
    unsigned long long m = n ? output(n / 2) : 0;
    printf("%d", (int)(n % 2));
    return m;
}

int main()
{
    unsigned long long number = 9223372036854775807;
    output(number);
    printf("\n");
}

输出:

0111111111111111111111111111111111111111111111111111111111111111

我还将类型更改为unsigned long long,它具有更好的位模式定义,并且%仍然会对负数做奇怪的事情.

I've also changed the type to unsigned long long which has a better defined bit pattern, and % does strange things for negative numbers anyway.

虽然,实际上,我在这里所做的只是滥用堆栈,以存储实际上是零和1的数组的方式.

Really though, all I'm doing here is abusing the stack as a way of storing what is really an array of zeros and ones.

这篇关于使用C的Long Long十进制二进制表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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