Calculation method for conversion between decimal and binary

1. Convert decimal to binary

Calculation method:

  1. Divide a decimal number by 2 to get the quotient and remainder (remainder is 0 or 1)
  2. Then the obtained quotient continues to be divided by 2 to obtain the quotient and remainder until the quotient is 0
  3. Finally, sort these remainders in reverse order

Note: The remainder of dividing 1 by any positive integer greater than 1 is 1

// 十进制数256 转二进制为100000000
256/2=1280
128/2=640
64/2=320
32/2=160
16/2=80
8/2=40
4/2=20
2/2=10
1/2=01 // 1除以任何一个大于1的正整数的余数都是1
将余数倒序排序就是二进制为:100000000

// 十进制数107转二进制为1101077
107/2=531
53/2=261
26/2=130
13/2=61
6/2=30
3/2=11
1/2=01 // 1除以任何一个大于1的正整数的余数都是1
将余数倒序排序就是二进制为:1101011

2. Convert binary to decimal

Calculation method:

  1. Counting from the last digit, multiply by 2 to the nth power
  2. The last digit is 2 to the 0th power, the penultimate digit is 2 to the power of 1, and the power of 2 is always + 1 until the first digit
  3. Finally add up all calculated sums

Note: Any non-zero number to the power of 0 is equal to 1

// 二进制100000000 转为十进制256
// 从最后一位开始算,为2的0次方,之后每次乘以2的上一次次方+1
0*20次方=0 // 任何非零数的0次方都等于1
0*21次方=0 
0*22次方=0 
0*23次方=0 
0*24次方=0 
0*25次方=0 
0*26次方=0 
0*27次方=0
1*28次方=256 // 等于1*2*2*2*2*2*2*2*2=256
// 最后相加 256+0+0+0+0+0+0+0+0=256

// 二进制1101011转为十进制107
// 从最后一位开始算,为2的0次方,之后每次乘以2的上一次次方+1
1*20次方=1 // 任何非零数的0次方都等于1
1*21次方=2 
0*22次方=0 
1*23次方=8 
0*24次方=0 
1*25次方=32
1*26次方=64  // 等于1*2*2*2*2*2*2=64
// 最后相加 64+32+0+8+0+2+1=107

Guess you like

Origin blog.csdn.net/weixin_43948460/article/details/131920224