简体   繁体   English

C使用联合将十进制数转换为二进制

[英]C convert decimal number to binary using union

I have this code: 我有以下代码:

#include <stdio.h>
#include <string.h>
int main(void)
{
    long long int n,b,t,j;
    while(scanf("%llu",&n) && n)
    {
        char a[2000]={0},c[2000]={0};
        b=0;
        int k=0;

        while(n>0)
        {
            a[b++]=(n%2)+48;
            if(n%2==1)
            k++;
            n=n/2;
        }
            a[b]='\0';
            j=strlen(a)-1;

        for(b=j,t=0;b>=0;b--)

            c[t++]=a[b];
            c[t]='\0';

        printf("The parity of %s is %d (mod 2).\n",c,k);
    }

return 0;
}

This code working perfect. 此代码工作完美。

Now I want to convert decimal number to binary using union in C 现在我想使用C中的并集将十进制数转换为二进制

How can I do that? 我怎样才能做到这一点?

You can't, that doesn't make any sense. 你不能,那没有任何意义。 Decimal and binary are representations of numbers. 十进制和二进制表示数字。 Ten cars in decimal is the same number of cars as ten cars in binary. 十进制的十个汽车与十进制的十个汽车相同。 It's precisely the same number. 这是完全相同的数字。 There's no way to use a union to change one integer representation to another. 无法使用并集将一个整数表示形式更改为另一个整数表示形式。

Since the number is not represented in decimal in memory, you have already accomplished this task, without even using a union. 由于数字在内存中没有用十进制表示,因此您已经完成了此任务,甚至没有使用联合。 If you want to obtain a binary textual representation: 如果要获取二进制文本表示形式:

unsigned n = 12345;

for (int i = sizeof(n) * CHAR_BIT - 1; i >= 0; i--) {
    putc('0' + ((n >> i) & 1), stdout);
}

Why? 为什么?

A union is merely a structure where all the members have the same location in memory (they overlap). 联合只是所有成员在内存中具有相同位置(它们重叠)的结构。

I'm not familiar with any typical approach for using a union when creating a binary string, I don't think that's (easily) possible at all. 我对创建二进制字符串时使用联合的任何典型方法都不熟悉,我认为这根本不可能(轻松)。

Perhaps you're confusing the use of unions when converting between floating point and integers (ugly but sometimes used to get at the bits for a floating point number)? 也许您在浮点数和整数之间转换时混淆了并集的使用(丑陋,但有时用于获取浮点数的位)?

#include <stdio.h>
#include <conio.h>
union calc
{
    struct {
        unsigned char bit0  : 1;
        unsigned char bit1  : 1;
        unsigned char bit2  : 1;
        unsigned char bit3  : 1;
        unsigned char bit4  : 1;
        unsigned char bit5  : 1;
        unsigned char bit6  : 1;
        unsigned char bit7  : 1;
    } bits;
   unsigned char numero;
};  
int main(int argc, char *argv[]) {
    union calc  c;
    scanf("%u",&c.numero);
    printf("%d%d%d%d%d%d%d%d",c.bits.bit7,c.bits.bit6,c.bits.bit5,c.bits.bit4,c.bits.bit3,c.bits.bit2,c.bits.bit1,c.bits.bit0);
    getch();
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM