This article describes the conversion between decimal and binary using Go

The first thing you need to understand is that the numbers we use are all decimal, and binary is only 0 and 1.

So let’s talk a little bit about converting from decimal to binary.

Method one: short division

For example, if we need to convert the value 23 to binary, we use short division.

I’m sure you know a little bit about base conversion before, and this is how it works.

Divide a decimal number by two, divide the resulting quotient by two, and so on until the quotient equals one or zero, taking the remainder of the division, which is the result of converting to binary.

So 23 to binary is 10111, just by reversing all the remainder

Convert decimal to binary using short division

Scheme 2: Use Go for transformation

The decimal implemented with GO is converted to binary

Int (n /= 2); int (n /= 2); int (n /= 2);

Because N/=2 is actually N=N/2, and your N is an int, the compiler will automatically convert a non-integer to an integer, and 19.5 into N is 19

So n is automatically converted to 11 on the second iteration of the loop, instead of 11.5.

The Strconv. Itoastrconv package is also used here to provide type conversions between strings and simple data types.

A simple type can be converted to a string, or a string can be converted to another simple type.

Since result is a string, Itoa needs to cast the returned value from int to string.

The final return value is 10111

Binary to decimal

Converting the 10111 binary to decimal is also simple

Look at the following calculation of 1 + 1 * 2 * 2 ^ 0 ^ ^ 2 + 1 + 1 * 2 * 2 0 ^ 3 + 1 * 2 ^ 4 = 1 + 2 + 4 + 0 + 16 = 23

Adhering to learning, blogging and sharing is the belief that Kakha has been upholding since she started her career. I hope the articles on the Internet can bring you a little help. I’m Kaka. See you next time.