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?
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 callstrconv.ParseInt()
, passing 16 as the base:Example testing it:
Output (try it on the Go Playground):
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.