[英]How do you convert a decimal to an 8-bit signed binary?
Say I need to convert the decimal -125 to a signed 8-bit integer, how do I do this?假设我需要将十进制 -125 转换为带符号的 8 位 integer,我该怎么做?
I'm a computing student and I'm struggling how to figure it out.我是一名计算机专业的学生,我正在努力解决这个问题。 I understand the basics of converting it to base 2 but I can't get the answer.我了解将其转换为基数 2 的基础知识,但我无法得到答案。
Thanks谢谢
A signed 8-bit integer reserves its highest order bit for the sign.带符号的 8 位 integer 保留其最高位作为符号。 1
indicates the number is negative, 0
indicates the number is positive. 1
表示负数, 0
表示正数。 Let's start there.让我们从那里开始。
The number you're trying to convert is -125
, so the first bit should be 1
.您要转换的数字是-125
,所以第一位应该是1
。
1XXX XXXX
For the next seven bits, we are going to see how many times the number they represent goes into the number we are trying to convert.对于接下来的七位,我们将查看它们代表的数字有多少次进入我们要转换的数字。
The second bit of our number represents 2^6
or 64
.我们数字的第二位代表2^6
或64
。 We ask how many times 64
can go into 125
and find that the answer is 1.953125
.我们问64
可以将 go 变成125
多少次,发现答案是1.953125
。
We cannot represent this number as a 1
or a 0
, but we can think about it like this:我们不能将这个数字表示为1
或0
,但我们可以这样想:
64 goes into 125 one time with a remainder of 0.953125 times (or 61) 64 进入 125 一次,余数为 0.953125 次(或 61)
Let's count the one time in our second bit and use the remainder 61
as our new number.让我们在第二位中计算一次,并使用余数61
作为我们的新数字。
11XX XXXX
Next is the third bit which represents 2^5
or 32
.接下来是代表2^5
或32
的第三位。 How many times can 32
go into 61
? 32
go 可以变成61
多少次? The answer is not a whole number, but 1.90625
so we follow the logic from the previous step again: using 1
as our third digit and 29
as our new number.答案不是整数,而是1.90625
,因此我们再次遵循上一步的逻辑:使用1
作为第三位数字,使用29
作为新数字。
111X XXXX
The fourth bit represents 2^4
or 16
which goes into 29
once with a remainder of 13
.第四位表示2^4
或16
一次进入29
余数13
。
1111 XXXX
The fifth bit represents 2^3
or 8
which goes into 13
once with a remainder of 5
.第五位表示2^3
或8
一次进入13
余数5
。
1111 1XXX
The sixth bit represents 2^2
or 4
which goes into 5
once with a remainder of 1
.第六位表示2^2
或4
进入5
一次,余数为1
。
1111 11XX
The seventh bit represents 2^1
or 2
which goes into 1 zero times.第 7 位表示2^1
或2
进入 1 零次。
1111 110X
The eighth and final bit represents 2^0
or 1
which goes into 1
once.第八位也是最后一位代表2^0
或1
,它进入1
一次。
1111 1101
Thus our 8-bit signed representation of -125
is 11111101
.因此,我们的-125
的 8 位有符号表示是11111101
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.