使用无符号字符和无字符串将十进制转换为16位二进制 [英] Converting a decimal to a 16 bit binary using unsigned char and without string

查看:327
本文介绍了使用无符号字符和无字符串将十进制转换为16位二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将操作数1和操作数2用作整数,我的代码将起作用。使用无符号char操作数1无效。你能帮我吗?

My code works if I use operand 1 and operand 2 as integers. Using unsigned char operand 1 does not work. Can you help me?

int ALU(unsigned char operand1, unsigned char operand2)
{
printf("Enter Operand 1(in decimal): ");
scanf("%d",&operand1);
printf("\nEnter Operand 2(in decimal): ");
scanf("%d",&operand2);

char bin16_1[]  = "0000000000000000";
int pos;
for (pos = 16; pos >= 0; --pos)
{
    if (operand1 % 2) 
    bin16_1[pos] = '1';
    operand1 /= 2;
}
printf("\n\nBinary Equivalence of Operand 1: %s",bin16_1);

如果我输入4096或512或65536作为十进制,则输出将是0000 0000 0000 00000

If I input 4096 or 512 or 65536 as decimal, the output will be 0000 0000 0000 00000 which is wrong.

推荐答案

char *reverse(char *str)
{
    size_t len = strlen(str);

    for (size_t pos = 0; pos < len / 2; pos++)
    {
        char tmp = str[pos];

        str[pos] = str[len - 1 - pos];
        str[len - 1 - pos] = tmp;
    }
    return str;
}

char *toBin(char *buff, uint16_t value, int pad)
{
    size_t nbits = 16;
    char *work_buff = buff;
    do
    {
        *work_buff++ = value & 1 ? '1' : '0';
        value >>= 1;
        nbits--;
    }while(value);
    if (pad)
    {
        while (nbits--)
        {
            *work_buff++ = '0';
        }
    }
    *work_buff = 0;
    return reverse(buff);
}

这篇关于使用无符号字符和无字符串将十进制转换为16位二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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