Home >Backend Development >Golang >Use Go to implement conversion between bases
“This article will introduce the use of Go to convert between decimal and binary
”
First of all, you must first Understand that the numbers we commonly use are all decimal, and binary only contains 0 and 1.
Then let’s briefly talk about how to convert decimal to binary.
Method 1: Short Division
For example, now we need to convert the value 23 into binary, we use short division to calculate.
I believe that everyone has more or less understood some base conversion before. The following figure shows the conversion process.
Divide a decimal number by two, and then divide the quotient by two, and so on until the quotient is equal to one or zero, then take the remainder of the division, which is the result of converting it to a binary number.
So 23 converted to binary is 10111, just reverse all the remainders
Option 2: Use Go for conversion
It is estimated in the picture above Most friends who are new to Go programming may have some doubts about n /= 2
. When this is passed in as an integer, the calculated data should be of floating point type. So how is this calculated? Woolen cloth!
Because N/=2 is actually N=N/2, and your N is an int type, the compiler will automatically convert the non-integer number into an integer type, and 19.5 will be put into N, which is 19
So when executing the second loop statement, n will automatically be converted to 11, instead of using 11.5 for calculation.
strconv.Itoa
The strconv package provides type conversion functions between strings and simple data types.
You can convert simple types to strings, and you can also convert strings to other simple types.
Because the result is a string type, Itoa will perform type conversion on the returned value when necessary, converting the int type to the string type.
The final return value is 10111
Convert binary to decimal
Convert this 10111
binary Converting to decimal is also very simple
See the following calculation1*2^0 1*2^1 1*2^2 0*2^3 1*2^4 = 1 2 4 0 16 = 23
##“Persistence in learning, persistence in blogging, and persistence in sharing are the beliefs that Kaka has always upheld since his career. I hope that Kaka’s articles can be seen in the huge Internet. Bringing you a little bit of help. I am Kaka, see you in the next issue. ”
golang tutorial"
The above is the detailed content of Use Go to implement conversion between bases. For more information, please follow other related articles on the PHP Chinese website!