#Hex to Binary

22 messages · Page 1 of 1 (latest)

tranquil swallow
#

Do you want a binary representation in the form of text or actual binary? gophereyes

prisma geode
#

actually it's working as expected
just without leading zeros?

lofty quarry
#

There's also encoding/hex and encoding/binary if you don't want to use bigint

prisma geode
lofty quarry
#

Looks like this is what they want no?

tranquil swallow
#

its in form of string

#

Hex string to binary string

lofty quarry
#

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

unborn light
#

a more efficient solution takes advantage of the fact that each hexadecimal position represents exactly four bits

prisma geode
#

@shadow rampart are input and output both string?

unborn light
#

though, there are a couple optimizations in there that are probably not obvious

prisma geode
#

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 :/

unborn light
#

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

prisma geode
#

I hoped I could do %b on byte slice but I think it's only for hexadecimal

unborn light
#

i would expect %b to format a byte slice by printing each element in binary with spaces between, all wrapped in []

prisma geode
unborn light
#

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 sunturtle