# Hex to Binary function

Hey there, where can I find a function to convert a hex string like “054C” into binary string like;
“0000010101001100”

I search the whole Google and found nothing. I got a Delphi function but I don’t know how to rewrite it in GO, below Delphi code;

``````function HexToBin(Hexadecimal: string): string;
const
BCD: array [0..15] of string =
('0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111');
var
I : integer;
begin
for I := Length(Hexadecimal) downto 1 do
Result := BCD[StrToInt('\$' + Hexadecimal[i])] + Result;
end;``````

And below my GO try, but I dunno how is that done in GO, I mean, the code line inside for loop;

``````func HexToBin(Hexadecimal string) string {
var BCD = string {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}
var Rst string
for I := len(Hexadecimal); I > 1; I-- {
Rst = BCD[StrToInt('\$' + Hexadecimal[i])] + Rst;
}
}``````

Could anyone help me with this line?

``Rst = BCD[StrToInt('\$' + Hexadecimal[i])] + Rst;``

Tnx.

Its easier to use `strconv.ParseUint` and `fmt.Sprintf`:

https://play.golang.org/p/qky7nbZjoI

If I put 4 bytes it gives me wrong result, example, If I put 1 hex byte, it should give me an 8 digit sequence like 0000 0000, 2 bytes = 0000 0000 0000 0000, 3 = 0000 0000 0000 0000 0000 0000…

https://play.golang.org/p/VepLWNEOEA

``````package main

import (
"fmt"
)

func Hex2Bin(in byte) string {
var out []byte
for i := 7; i >= 0; i-- {
b := (in >> uint(i))
out = append(out, (b%2)+48)
}
return string(out)
}

func main() {
for r := 0; r < 256; r++ {
fmt.Printf("%v: %v\n", r, Hex2Bin(byte(r)))
}
}``````

The Go equivalent of StrToInt is strconv.ParseInt. Instead of adding a prefix to indicate the base, you should specify the base directly, as the second parameter.

Since ParseInt can return an error, you can’t use it directly in the array subscript. You need to put it on a separate line and handle the error:

``````v, err := strconv.ParseUint(Hexadecimal[i:i+1], 16, 8)
if err != nil {
return "", err // or whatever you decide to do with the error
}
Rst = BCD[v] + Rst
``````

how can I transform string to bin? just like hex2bin in PHP. (“96659ee67b39f2d9c3418cddaa307c5e1640a6e883f3fa9540e846ad1221b990ba9ac28ebb2e4daf2ea039cc929b9e7d6c9b3a7”)

just a hex string itself

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.