Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

整型数数据在内存中的存储 #133

Open
codcodog opened this issue Jul 20, 2022 · 0 comments
Open

整型数数据在内存中的存储 #133

codcodog opened this issue Jul 20, 2022 · 0 comments
Labels

Comments

@codcodog
Copy link
Owner

整型数数据在内存中的存储

基本概念

「机器数」指一个数在计算机中的二进制表示形式.

「机器数」是带符号的,在计算机用一个数的最高位存放符号,正数为0,负数为1.

将带符号位的机器数对应的真正数值称为机器数的「真值」.

例如:0000 0001 的「真值」=> +000 0001 = +1,1000 0001 的「真值」=> -000 0001 = –1

「原码」:将十进制数直接翻译为二进制数.
「反码」:原码的符号位不变,其他位按位取反.
「补码」:反码+1.

对于正数来说,反码补码都与原码相同.
而对于负数来说,则符合上述所说的规则:

  • 原码,将十进制数字直接翻译为二进制
  • 反码,原码的符号位不变,其他位按位取反
  • 补码:反码+1

反码和补码设计出来就是为了表示负数的,使计算机更好的去计算.

对于整型来说,整型在内存中实际上是以「补码」的形式进行存储的.

两个整数使用补码进行运算的时候,就可以不关心它们的符号位了,
将它们的位直接相加就好了,就能得到正确的结果.

整数转换问题

整数从高位转低位,例如:

a := int16(256)
b := int8(a)
fmt.Println(b)  // 输出:0

256 int16 在内存存储为:0000 0001 0000 0000
转为 int8 的时候,直接截取8位为:0000 0000

整数从低位负数转高位正数,例如:

c := int8(-8)
d := uint16(c)
fmt.Println(d) // 输出:65528

-8 int8 在内存存储为:1111 1000
转为 uint16 的时候,为:1111 1111 1111 1000

这里为什么不是 0000 0000 1111 1000
从低位负数转高位正数时,剩余不够的位数会置1,所以是 1111 1111 1111 1000
暂时没有找到资料为什么会这样转换

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant