Home  >  Article  >  How to convert hexadecimal to binary in go language

How to convert hexadecimal to binary in go language

DDD
DDDOriginal
2023-06-09 09:49:351384browse

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.

How to convert hexadecimal to binary in go language

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn