#Hex to Binary
22 messages · Page 1 of 1 (latest)
actually it's working as expected
just without leading zeros?
There's also encoding/hex and encoding/binary if you don't want to use bigint
encoding/binary is not for string conversion though
Looks like this is what they want no?
I would try using encoding/hex to convert it to bytes and then I think you could fmt that to binary representation
The problem with the number is that it won't pad it
Not sure if that'll work actually might still not pad it hmm
a more efficient solution takes advantage of the fact that each hexadecimal position represents exactly four bits
@shadow rampart are input and output both string?
https://go.dev/play/p/NgOKsxoTAAR is about what it looks like if you just write the loop, as they say
though, there are a couple optimizations in there that are probably not obvious
it does but bit hack-y
func hexbin(str string) (string, error) {
var data []byte
var err error
var build strings.Builder
if len(str)%2 != 0 {
data, err = hex.DecodeString("0" + str)
if err != nil {
return "", err
}
fmt.Fprintf(&build, "%04b", data[0])
data = data[1:]
} else {
data, err = hex.DecodeString(str)
if err != nil {
return "", err
}
}
for _, char := range data {
fmt.Fprintf(&build, "%08b", char)
}
return build.String(), nil
}
untested :/
i would say that what you are doing is niche, and i'm not at all surprised that there is nothing built-in for it
I hoped I could do %b on byte slice but I think it's only for hexadecimal
i would expect %b to format a byte slice by printing each element in binary with spaces between, all wrapped in []
I think I can optimize this further
but might not be worth the effort
I'm not sure if they care about it so much in the first place
i agree there are more optimizations that could be done and that they're not worth the effort
and yeah, ranging over len(hex) is more correct
technically it will still reject invalid inputs as it's written, but it's only written the way it is because i started by ranging over the string and then decided to range over bytes instead and forgort to fix the loop 
