我们可以将负数的整数分配给无符号整数吗?

标签 c

#include<stdio.h>
#include<conio.h>
main()
{
    int i=-5;
    unsigned int j=i;
    printf("%d",j);
    getch();
}

O/p
-----
-5

#include<stdio.h>
#include<conio.h>
main()
{
    int i=-5;
    unsigned int j=i;
    printf("%u",j);
    getch();
}

O/p
===
4255644633

这里我没有得到任何编译错误。

当使用标识符 %d 打印时它给出 -5,当使用 %u 打印时它打印一些垃圾值。

我想知道的是

1) 为什么编译器在将带负数的整数分配给 unsigned int 时忽略。

2) 如何将有符号转换为无符号?

最佳答案

“我们”是谁?

没有“垃圾值”,这可能只是将有符号整数的位视为无符号整数的结果。通常 two's complement对于许多负值,将导致非常大的值。尝试以十六进制打印值以更清楚地查看模式,十进制通常难以破译。

关于我们可以将负数的整数分配给无符号整数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20547327/

相关文章:

c - 传递带有参数的函数作为参数

将字符连接到空字符串

c - 使用消息队列的 C 生产者/消费者中的段错误

c - 为什么这个 OpenMP 并行 for 循环不能正常工作?

c++ - 使用一个 Makefile 构建多个共享库

c - 实现命令行参数

c - GCC -nostdlib 失败, undefined reference `__libc_csu_fini'

c - PKCS5_PBKDF2_HMAC : binary password

c - 静态 pthreads 互斥体初始化

c - 指针显式转换为 long long