将负二进制转换为十进制

时间:2014-10-05 23:05:08

标签: c binary

过去几个小时我一直试图将负二进制数转换为第一位为1到十进制。二进制补码转换似乎是不可能的,但我相信必须有一些更简单的方法来做到这一点,因为这只是C语言中初学者类的开始。

int power;
int count = 0;
int length = strlen(value);
int result = 0;
int negResult = 0;
int i = length - 1;
int j;

if (value[0] == '1') {
  for (; i >= 0; i--) {
    if (value[i] == '1')
    result += 1;
    result << 1;
  }
  printf("%d\n", result);
  result = ~result;
  result += 1;
  printf("%d\n", result);
  for (j = 8; j > 0; j--) {
    if (result << (8-j) == 1) {
      power = (int) pow(2,count);
      negResult += power;
    }
    count++;
  }

  printf("-%d\n", negResult);
}
else {
  for (; i >= 0; i--) {
    if (value[i] == '1') {
      power = (int) pow(2,count);
      result = result + power;
    }
    count++;
  }

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

我通过了:

binary_to_decimal("10011011");

然后我得到5然后-5,然后每个printf得到-0。

我没有包含实际将其转换为小数的代码,因为对于正二进制文件,它工作正常,我相信一旦二进制补码工作,它也应该适用于负二进制文件。

2 个答案:

答案 0 :(得分:2)

您可能不清楚temp += '0'正在做什么。它没有创建一个字符串,而是它偏移了一个未初始化的指针,并且当你在temp2[j]中实际使用它时,它是segfault的原因。要使用我认为您想要的字符串,请查看strcat()

我会把它扔掉并重新开始。不要在字符串中操纵字符,只需将字符串转换为二进制字符串即可。编写一些代码来将输入字符串从第一个字符移到最后一个字符。为您的答案保留result整数,最初为0。当您浏览字符串时,请转移result << 1,然后如果您看到字符'1',请向1添加result个数字。如果您在字符串中看到'0',请不要添加任何内容,但无论如何都要先左移。

这将为您提供一个二进制,无论你有多少位。对于负数(最上面的(第一个)位=&#39; 1&#39;),您需要通过OR-ing&#39; 1&#39;来签名扩展。在符号位上方的所有位中,按位反转结果并添加1.在纸上检查以查看其工作原理,并注意输入字符串不能太长。祝全班同学好运。

int length = strlen(value);
unsigned int result = 0;
unsigned int signExtend;
unsigned int negResult = 0;

// assemble incoming chars as bits in an unsigned int
for (int i=0;i<length;i++) {
    result = result << 1;
    if (value[i] == '1')
        result += 1;
    }
printf("0x%x, %d\n", result, result); // see it is a hex number and a decimal

// if negative, convert to positive number
if (value[0] == '1') {
    // first, sign-extend
    signExtend = (1 << (length-1));
    signExtend -= 1;
    signExtend = ~signExtend;
    result |= signExtend;
    printf("signExtend mask = 0x%x, sign-extended number = %x\n", signExtend, result);

    // then, two's complement
    negResult = ~result;
    negResult += 1;

    // show the result with the '-' sign explicitly added:
    printf("result is -%d\n", negResult);

    // but actually, once you have sign extended,
    // you can cast the result as signed and just print it:
    printf("result as signed int = %d\n", (int)result);
} else {
    // positive result, just print it
    printf("result is %d\n", result);
}

答案 1 :(得分:1)

这是我怎么做的

 int btd(char *str)
 {
    int i , l = strlen(str) , neg = 0;
    int res = 0;

    for(i = 0 ; i < l ; i++)
    {
            if(!i)
            {
                    if(str[i] == '1');
                            neg++;
                    continue;
            }
            if(str[i] == '1')
            {
                    res <<= 1;
                    res |= 1;
            }
            else
                    res <<= 1;

    }
    if(neg)
            res *= -1;
    return res;
 }