使用无符号整数的负数会发生什么? [英] what happens with the negative of an unsigned integer?

查看:924
本文介绍了使用无符号整数的负数会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于文字0xffffffff需要32位数字,它可以表示为一个unsigned int,但不能作为一个有符号的int,并且是unsigned int类型。但是无符号整数的负数会发生什么?

  #include< iostream> 
#include< limits>

int main()
{
int N [] = {0,0,0};

if(std :: numeric_limits< long int> :: digits == 63 and
std :: numeric_limits< int> :: digits == 31 and
std :: numeric_limits< unsigned int> :: digits == 32)
{
for(long int i = -0xffffffff; i; --i)
{
N [i] 1;
}
}
else
{
N [1] = 1;
}

std :: cout<< N [0] << N [1]< N [2];
}

输出: 010

解决方案

根据定义,没有负无符号整数。



超过无符号整数的下限,从最高可能值开始的值回绕。



当将signed值转换为未签名值时,也会触发此机制。



因此,有符号值-1转换为无符号值 $ maximumUnsignedValue 。类似地,签名值 - $ maximumSignedValue 将转换为未签名值 $ maximumUnsignedValue - $ maximumSignedValue + 1 p>

Since the literal 0xffffffff needs 32 digits, it can be represented as an unsigned int but not as a signed int, and is of type unsigned int. But what happens with the negative of an unsigned integer?

#include <iostream>
#include <limits>

int main()
{
  int N[] = {0,0,0};

  if ( std::numeric_limits<long int>::digits==63 and
    std::numeric_limits<int>::digits==31 and
    std::numeric_limits<unsigned int>::digits==32 )
  {
    for (long int i = -0xffffffff; i ; --i)
    {
      N[i] = 1;
    }
  }
  else
  {  
    N[1]=1;
  }

  std::cout << N[0] <<N [1] << N[2];
}

output : 010

解决方案

There is no such thing as a negative unsigned integer, by definition.

When you go beyond the lower bounds of an unsigned integer, the value "wraps around" starting from the highest possible value. (The same occurs vice versa).

This mechanism is also triggered when converting a negative "signed" value to an unsigned one.

So, the signed value -1 is converted to the unsigned value $maximumUnsignedValue. Similarly, the signed value -$maximumSignedValue is converted to the unsigned value $maximumUnsignedValue - $maximumSignedValue + 1.

这篇关于使用无符号整数的负数会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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