Unsigned int取负值 [英] Unsigned int takes negative values

查看:68
本文介绍了Unsigned int取负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么unsigned int取负值吗? unsigned int 应该只取正值.

Can someone explain why unsigned int is taking a negative value? An unsigned int should take only positive values.

来自维基百科:

word,long,doubleword,longword,int

word, long, doubleword, longword, int

无符号:从0到4,294,967,295,等于2 ^ 32 − 1

Unsigned: From 0 to 4,294,967,295 which equals 2^32 − 1

#include <stdio.h>
typedef unsigned int uint32;

int main()
{
     uint32 i;
     int x = -1;
     i = x%32;
     printf("\n\n Value of uint32 i = %d", i);
     return (0);
}

输出:

Value of uint32 i = -1

下面是我在cpp标准中找到的解释,我无法解释.

Below is the explanation which I found in cpp standard, which I am unable to interpret.

对于每个有符号整数类型,都存在一个对应的(但不同的)无符号整数类型:"unsigned char","unsigned short int","unsigned int"和"unsigned long int",每种类型都占用与相应的有符号整数类型40相同的存储量并具有相同的对齐要求(3.9);也就是说,每个有符号整数类型与其对应的无符号整数类型具有相同的对象表示形式.有符号整数类型的非负值范围是相应的无符号整数类型的子范围,并且每个相应的有符号/无符号类型的值表示应相同.

For each of the signed integer types, there exists a corresponding (but different) unsigned integer type: "unsigned char", "unsigned short int", "unsigned int", and "unsigned long int," each of which occupies the same amount of storage and has the same alignment requirements (3.9) as the corresponding signed integer type40) ; that is, each signed integer type has the same object representation as its corresponding unsigned integer type. The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the value representation of each corresponding signed/unsigned type shall be the same.

声明为无符号的4个无符号整数应服从2n模运算定律,其中n是该特定整数大小的值表示形式中的位数.

4 Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer

40)有关类型之间的对应关系以及指定类型的类型说明符序列,请参见7.1.5.2.

40) See 7.1.5.2 regarding the correspondence between types and the sequences of type-specifiers that designate them.

41)这意味着无符号算术运算不会溢出,因为无法以结果无符号整数类型表示的结果的模数要比可以由结果无符号整数表示的最大值大一个模数而减少类型.

41) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

推荐答案

您为 printf 使用了错误的标志.它应该是%u .

You are using the wrong flag for printf. It should be %u.

printf("\ n \ n uint32的值i =%u",i);

这篇关于Unsigned int取负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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