Home >Common Problem >How to convert hexadecimal to binary in go language
Steps for converting Go language hexadecimal to binary: 1. Create a table corresponding to hexadecimal and binary; 2. Traverse the hash character by character and convert a single character into binary; 3. Fill in if it is less than 4 digits , using binary to represent hexadecimal requires 4 digits; 4. Just combine them in order.
There are many ways to implement it, such as creating a table corresponding to hexadecimal and binary, traversing and querying the hash strings one by one and then combining them.
I used another method here. The general idea is as follows:
Traverse the hash character by character and convert a single character into binary;
If it is less than 4 digits, fill it; (2^4 = 16, using binary to represent hexadecimal requires 4 digits)
Combine in order;
Code example:
package util import( "strings" "strconv" ) func hash2bin(hash string)(string,int,error){ binary_string := "" for _, char := range hash{ char_hex,err:= strconv.ParseInt(string(char),16,8) if err!=nil{ return "",0,err } char_bin := "" for ; char_hex > 0; char_hex /=2{ b := char_hex % 2 char_bin = strconv.Itoa(int(b))+char_bin } fill := 4-len(char_bin) for fill>0{ char_bin = "0" + char_bin fill -= 1 } binary_string += char_bin } return binary_string,len(binary_string),nil }
The above is the detailed content of How to convert hexadecimal to binary in go language. For more information, please follow other related articles on the PHP Chinese website!