c - K&R 练习 3-4 : Negative Numbers Represented In Binary

标签 c binary bit

我很难理解这个练习:

In a two's complement number representation, our version of itoa does not handle the largest negative number, that is, the value of n equal to -(2^(wordsize-1)). Explain why not. Modify it to print that value correctly, regardless of the machine on which it runs.

这是 itoa 最初的样子:

void reverse(char s[], int n)
{
  int toSwap;
  int end = n-1;
  int begin = 0;

  while(begin <= end) // Swap the array in place starting from both ends.
    {
      toSwap = s[begin];
      s[begin] = s[end];
      s[end] = toSwap;

      --end;
      ++begin;
    }
}

// Converts an integer to a character string.
void itoa(int n, char s[])
{
  int i, sign;
  if ((sign = n) < 0)
    n = -n;
  i = 0;
  do
    {
      s[i++] = n % 10 + '0';
    } while ((n /= 10) > 0);

  if (sign < 0)
    s[i++] = '-';
  s[i] = '\0';
  reverse(s, i);
}

我找到了这个答案,但我不明白其中的解释: http://www.stevenscs.com/programs/KR/ $progs/KR-EX3-04.html

Because the absolute value of the largest negative number a word can hold is greater than that of the largest positive number, the statement early in iota that sets positive a negative number corrupts its value.

他们是说负数由于符号的原因比没有符号的正数包含更多的位吗?为什么乘以 -1 会影响大负数的存储方式?

最佳答案

在二进制补码表示中,可以表示的值范围是 -2<sup>n-1</sup>2<sup>n-1</sup>-1 。因此,使用 8 位,您可以表示 -128 到 127 范围内的值。这就是短语“一个字可以容纳的最大负数大于最大正数”的含义。

仅用 3 位进行说明以使其更清晰:

Value    Bits
-----    ----
    0    000
    1    001
    2    010
    3    011
   -4    100
   -3    101
   -2    110
   -1    111

使用 3 位,我们无法表示 4二进制补码,所以 n = -n;不会给我们预期的结果1。这就是为什么原来的atoi上面的实现无法处理 INT_MIN .

<小时/>

  1. 有符号整数溢出的行为是未定义,这意味着没有固定的结果。

关于c - K&R 练习 3-4 : Negative Numbers Represented In Binary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39258583/

相关文章:

java - “如果”和 'Else' 在 Java 中不起作用?

c# - 如何在C#中设置ushort的最左和最右位

c - 使用 strtok() 在 c 中将字符串标记两次

c - *arr[] 和 **arr 的区别

c - C 中的整数加法

c - 用C语言将原始二进制文件写入文件

c# - 从音频文件C#中提取信息

c - C 中的 Trie : Pointer detected as null. 导致内存泄漏

c - 如何将指针设置为二进制文件中的字符串?

java - Long.toBinaryString 未返回 827.0 的预期二进制字符串