2017-03-16 84 views
1

所以有这样的代码如何将十进制转换为二进制的64位?

int main() 
{ 
    int n, c, k; 

    printf("Enter an integer\n"); 
    scanf("%d", &n); 

    printf("%d in binary is:\n", n); 

    for (c = 31; c >= 0; c--) 
    { 
    k = n >> c; 

    if (k & 1) 
     printf("1"); 
    else 
     printf("0"); 
    } 

    printf("\n"); 

    return 0; 

} 

它转换成十进制二进制但仅在32位。当我将它改为64位时,它不起作用(它似乎只是32位结果的两倍)。同时它可以正常工作8或4位等。 我做错了什么?

+1

你是如何转换为64位? 'c = 63'? – AntonH

+1

@AntonH:除非'int'是64位,否则调用未定义的行为。 – Olaf

+1

使用''和固定大小类型。 –

回答

2

它将十进制转换为二进制,但只有32位。当我将它改为64位时,它不起作用(它似乎只是32位结果的两倍)。

问题就在这里。

int n, c, k; 

    printf("Enter an integer\n"); 
    scanf("%d", &n); 

nint其可以是作为16位的小。它可能是64位,但可能是32位。当你尝试输入64位数字时,你会得到垃圾。

#include <stdio.h> 

int main() { 
    int n; 

    printf("sizeof(int) == %zu\n", sizeof(int)); 

    printf("Enter an integer\n"); 
    scanf("%d", &n); 

    printf("n = %d\n", n); 
} 

$ ./test 
sizeof(int) == 4 
Enter an integer 
12345678901 
n = -539222987 

相反,可以使用一个long long int它具有64位或从stdint.h这正是64位int64_t的最小尺寸。我倾向于在代码中使用显式宽度类型,这需要特定的宽度才能使读者更加明白。

long long int使用%lldscanfprintfint64_t使用macros from inttypes.h。下面的代码利用C自动连接常量字符串; "foo" "bar""foobar"是等同的。

#include <stdio.h> 
#include <stdint.h> 
#include <inttypes.h> 

int main() { 
    int64_t n; 

    printf("Enter an integer\n"); 

    scanf("%"SCNd64, &n); 

    printf("n = %"PRId64"\n", n); 
} 


$ ./test 
Enter an integer 
12345678901 
n = 12345678901 
+1

'%lld'不一定是固定宽度类型的正确转换类型说明符。使用'inttypes.h'中的宏。顺便说一句。一些实现具有固定宽度类型名称的内置类型('stdint.h'只是'typedefs'这些内置名称的标准名称),因此它们明显不同于标准类型。 – Olaf

+0

@Olaf谢谢!我会解决这个问题。 – Schwern

0

问题是您的变量的数据类型。它们是整数。使用sizeof(int)检查您的平台的数据类型大小。

当您更改为64位时,这些变量不能保存64位值。

HTH!

0

下面的代码是处理问题的一种方法:

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

int main(void) 
{ 
    long long unsigned int n; 
    long long   int c; 
    long long unsigned int k; 

    printf("Enter an integer\n"); 
    if(1 != scanf("%llu", &n)) 
    { 
     perror("scanf for 64 bit number failed"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, scanf successful 

    printf("%llu in binary is:\n", n); 

    for (c = 63; c >= 0; c--) 
    { 
     k = n >> c; 

     if (k & 1) 
      putc('1', stdout); 
     else 
      putc('0', stdout); 
    } 

    printf("\n"); 

    return 0; 
} // end function: main 

,这里是从程序的典型运行输出:

Enter an integer 
6789097860397846 
6789097860397846 in binary is: 
0000000000011000000111101010011000000110010100000111101100010110 
+0

注意:以上是在ubuntu linux 16.04上运行gcc用来编译和链接的。 – user3629249

相关问题