char 和 unsigned 与int 之间的转换

    xiaoxiao2025-05-23  8

    预备知识:整数在计算机中的表示

    整数在计算机中是以二进制补码的方式表示的,以int型为例: int有4个字节,最高位为符号位,即正数为0xxx xxxx  xxxx xxxx  xxxx xxxx  xxxx xxxx b ,例如: <span style="font-size:18px;">int n = 3;</span> 在计算机里存储为0000 0000  0000 0000  0000 0000  0000 0011b; 负数为1xxx xxxx  xxxx xxxx  xxxx xxxx  xxxx xxxx b,即将该负数的绝对值按位取反,然后加1,例如: <span style="font-size:18px;">int n = -3;</span> 在计算机里存储为1111 1111  1111 1111  1111 1111 1111 1101b;

    int型转换为char和unsigned char

    因为char 和unsigned char型都是一个字节,int型是四个字节的,从int 型到char 或 unsigned char型的转换都是直接将int的最低字节赋予char 或 unsigned char;例如: char c = 3; unsigned char uc= 3;3是int型,其在计算机里的存储为 0000 0000  0000 0000  0000 0000  0000 0011b;所以 c 和 uc 在计算机里的存储都为 0000 0011b,由于是正数,故值都为3; 有例如: char c = -3; unsigned char uc= -3;-3是int 型,其在计算机里的存储为 1111 1111  1111 1111  1111 1111 1111 1101b;所以c和uc在计算机里的存储都为1111 1101b;但由于char是有符号的,unsigned char 是无符号的;char c的最高位为符号位,符号位1表示负数,0表示正数,所以c的值为-3;而unsigned char uc是无符号的,所以值为253;

    char和unsigned char 转换为int 型

    由于char或者unsigned char是一个字节的,int型是四个字节的,当char 或者 unsigned char向int 型转换的时候,高的三个字节计算机怎么处理呢? 1、因为char是有符号的,所以int 的高三个字节都是以char的最高位(符号位去填充),例如: 当c是char型,并且在计算机里存储为1111 1101b时, int n = c;n在计算机里的存储为: 1111 1111  1111 1111  1111 1111 1111 1101b,又例如: 当c是char型,并且在计算机里存储为0000 0011b时, int n = c; n在计算机里的存储为:0000 0000  0000 0000  0000 0000  0000 0011b; 2、因为unsigned char 是无符号的,所以int 的高三个字节都是以0填充,例如: 当uc是unsigned char型,并且在计算机里存储为1111 1101b时, int n = uc;n在计算机里的存储为: 0000 0000  0000 0000  0000 0000 1111 1101b,又例如: 当uc是unsigned char型,并且在计算机里存储为0000 0011b时, int n = uc;n在计算机里的存储为:0000 0000  0000 0000  0000 0000  0000 0011b;
    转载请注明原文地址: https://ju.6miu.com/read-1299164.html
    最新回复(0)