I have a string that looks like this "090A0B0C"
and I would like to convert it to a slice that looks something like this [9, 10, 11, 12]
. How would I best go about doing that?
I don't want to convert a single hex char tuple to a single integer value. I want to convert a string consisting of multiple hex char tuples to a slice of multiple integer values.
You can also implement hex encoding and decoding yourself, in case you want to avoid the dependency on the
hex
crate:Note that the
decode_hex()
function panics if the string length is odd. I've made a version with better error handling and an optimised encoder available on the playground.You could use the hex crate for that. The decode function looks like it does what you want:
The above will print
[9, 10, 11, 12]
. Note thatdecode
returns a heap allocatedVec<u8>
, if you want to decode into an array you'd want to use thedecode_to_slice
function, which is not yet released on crates.io or theFromHex
trait: