无符号整数如何工作 [英] How do unsigned integers work

查看:112
本文介绍了无符号整数如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我对unsigned int(或诸如NSUIntegeru_int_blah之类的东西,但我假设它们都是同一事物的typedef)如何工作感到好奇.例如,当它们的值降到零以下时,是否会产生过激肽?会发生错误吗?一个具体的例子是将值间接设置为负数.

As the title suggests, I am curious about how an unsigned int (or things like NSUInteger, u_int_blah, but I assume these are all typedefs of the same thing) works. For example, when their value drops below zero, is an exeption raised? Will an error occur? One specific example of this would be indirectly setting the value to a negative number.

for (unsigned int x = 5; x > -10; x--) {
    // will x ever reach below zero, or will the loop terminate
}


另外,间接设置它的另一种方法是让用户输入它.


Also, another way to indirectly set it would be to have the user input it.

printf("Enter a number");
unsigned int x;
scanf("%ud", &x); // user enters something like -29


所以说真的,我有三个问题.停止操作,并将unsigned int分配给负数(unsigned int x = - 3).如何实现此行为(通过编译器或其他方式).当一个无符号的int被(直接或间接地)赋给一个负值时会发生什么.数据损坏了吗?它会溢出吗?
谢谢


So really, I have three questions. What stops and unsigned int from being assigned to a negative number (unsigned int x = - 3). How is this behavior implemented (by the compiler, or by other means). What happens when an unsigned int is assigned (directly or indirectly) to a negative value. Is the data corrupted? Does it overflow?
Thankyou

推荐答案

分配负数时

unsigned int = -1;

您得到的号码将是4294967295,或4 ^ 8 -1

The number you got will be 4294967295, or 4^8 -1

因为整数的大小为4个字节,或4 ^ 8 = 4294967296

because the size of integer is 4bytes, or 4^8 = 4294967296

如果为负数,则整数将环绕该数字

The integer will wrap around this number if it is negative

这篇关于无符号整数如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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