基本类型转换(无符号数转换成浮点需关注) |
您所在的位置:网站首页 › python无符号转有符号 › 基本类型转换(无符号数转换成浮点需关注) |
1. 有符号数的转换 有符号数的转换中,如果从较低类型转换到较高类型,将进行符号扩展,例如一个值从short int(16位)转换到long类型,如果这个数是正数,则最高位为0,从16位扩展到32位时,扩展的高16位用0填充,即将符号位0进行扩展,这样扩展后的32位整数和原来的整数值是一样的。如果该数为负数,则最高位为1,从16位扩展到32位时,扩展的高16位用1填充,即将符号位1进行扩展,这样扩展后的32位整数和原来的整数值是也是一样的。 如果从较高类型转换到较低类型,将抛弃高位,直接将低位复制过来,例如一个值从int(假定为32位)转换到short int型(16位),系统将抛弃高16位,取低16位的值作为转换后的值。 浮点数类型和整数类型转换比较复杂,因为它们的内部表示方式不同,转换时它们不是简单的符号位扩展或者高位截断,它们首先需要进行内部表示方式的转换。左表是有符号数类型转换的所有情况。 从 到 方法 char short 符号位扩展 char long 符号位扩展 char unsigned char 最高位失去符号位意义,变为数据位 char unsigned short 符号位扩展到short;然后从short转到 unsigned short char unsigned long 符号位扩展到long; 然后从long 转到unsigned long char float 符号位扩展到long; 然后从long 转到float char double 符号位扩展到long; 然后从long 转到double char long double 符号位扩展到long; 然后从long 转到long double short char 保留低位字节 short long 符号位扩展 short unsigned char 保留低位字节 short unsigned short 最高位失去符号位意义,变为数据位 short unsigned long 符号位扩展到long; 然后从long转到unsigned long short float 符号位扩展到long; 然后从long 转到float short double 符号位扩展到long; 然后从long 转到double short long double 符号位扩展到long; 然后从long 转到double long char 保留低位字节 long short 保留低位字节 long unsigned char 保留低位字节 long unsigned short 保留低位字节 long unsigned long 最高位失去符号位意义,变为数据位 long float 使用单精度浮点数表示。可能丢失精度。 long double 使用双精度浮点数表示。可能丢失精度。 long long double 使用双精度浮点数表示。可能丢失精度。
2. 无符号数的转换 无符号数转换相对简单一些,它没有符号位,当低级类型向高级类型转换时,只需要将高位补0,高级类型向低级类型转换同有符号数。左表是无符号数类型转换的所有情况。 从 到 方法 unsignedchar char 最高位作为符号位 unsigned char short 0扩展 unsigned char long 0扩展 unsigned char unsigned short 0扩展 unsigned char unsigned long 0扩展 unsigned char float 转换到long; 再从 long 转换到float unsigned char double 转换到long; 再从 long 转换到double unsigned char long double 转换到long; 再从 long 转换到double unsigned short char 保留低位字节 unsigned short short 最高位作为符号位 unsigned short long 0扩展 unsigned short unsigned char 保留低位字节 unsigned short unsigned long 0扩展 unsigned short float 转换到long; 再从 long 转换到float unsigned short double 转换到long; 再从 long 转换到double unsigned short long double 转换到long; 再从 long 转换到double unsigned long char 保留低位字节 unsigned long short 保留低位字节 unsigned long long 最高位作为符号位 unsigned long unsigned char 保留低位字节 unsigned long unsigned short 保留低位字节 unsigned long float 转换到long; 再从 long 转换到float unsigned long double convert directly to double unsigned long long double 转换到long; 再从 long 转换到double
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |