arraysgohexrune

How to convert a fixed-length array of hexadecimal runes to a single integer


Given an array of runes which is a string encoded in hexadecimal, how can I convert it to a single integer. For example:

var digits [8]rune = "00000010"
magicFunction(digits)
// gives 16

var digits2 [8]rune = "deadbeef"
magicFunction(digits2)
// gives 3735928559

Go's encoding/hex package seems like it can only convert to a byte array (with Decode or DecodeString).

I could cast the rune array to a string and then use DecodeString, but I cannot work out how to then get an integer from the byte array it produces. The array will be a fixed length (8), so I don't need a variable array, I want a single value!

Short of reimplementing a hex decode algorithm, is there a proper/good way to do this?


Solution

  • Note that holding a number in a [8]rune looks strange and is inefficient. But if you must...

    If performance is not critical, simply convert your runes input to string, and call strconv.ParseInt(), passing 16 as the base:

    func magicFunction(rs [8]rune) (uint32, error) {
        x, err := strconv.ParseInt(string(rs[:]), 16, 64)
        return uint32(x), err
    }
    

    Example testing it:

    var digits [8]rune = [8]rune{'0', '0', '0', '0', '0', '0', '1', '0'}
    fmt.Println(magicFunction(digits))
    // gives 16
    
    var digits2 [8]rune = [8]rune{'d', 'e', 'a', 'd', 'b', 'e', 'e', 'f'}
    fmt.Println(magicFunction(digits2))
    // gives 3735928559
    

    Output (try it on the Go Playground):

    16 <nil>
    3735928559 <nil>
    

    If performance does matter: then do it "by hand": have a number holding the result, and on each digit shift left by 4, convert the rune to its numerical value and bitwise OR it with the variable.