Search code examples
rustreversepublic-keysecp256k1

How do I reverse a hex string?


Given a hex string, such as "d59c168e05df4757", how can I reverse the bytes of this string, so as to read [57, 47, df, 05, 8e, 16, 9c, d5]?

Using the as_bytes() method converts each individual character into a byte value, rather than the two-character hex representation.

From bytes representation I have tried the following without success:

let bytes = vec![213, 156, 22, 142, 5, 223, 71, 87];
let bytes_reversed = bytes.iter().rev();
println!("Bytes reversed: {:x?}", bytes_reversed);
//Prints: Bytes reversed: Rev { iter: Iter([d5, 9c, 16, 8e, 5, df, 47, 57]) }

Solution

  • Answering my own question - the following approach works to reverse the bytes of a hex string:

    1. Convert hex string to bytes
    2. Create a new vector
    3. Use iter().rev() in a for loop and push each iteration into the new vector

    Example code below, using parse_hex function defined in answer to this question:

    let hex_string: String = String::from("d59c168e05df4757");
    let string_to_bytes = parse_hex(&hex_string);
    println!("Hex string as bytes: {:?}", string_to_bytes); //Prints: [213, 156, 22, 142, 5, 223, 71, 87]
    let mut bytes_reversed = Vec::new();
        for i in string_to_bytes.iter().rev() {
            bytes_reversed.push(i);
        }
    println!("Bytes reversed: {:x?}", bytes_reversed); //Prints: [57, 47, df, 5, 8e, 16, 9c, d5]