0

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]) }
Isambard_FA
  • 97
  • 13

2 Answers2

1

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]
Isambard_FA
  • 97
  • 13
0

This can also be solved using only string operations to get a Vec with the reversed hex strings ["57", "47", "df", "05", "8e", "16", "9c", "d5"]
or as reversed String "5747df058e169cd5":

let hex = "d59c168e05df4757"
    .chars()
    .collect::<Vec<char>>()
    .chunks(2)
    .map(|c2| c2.iter().collect::<String>())
    .rev()
    .collect::<Vec<String>>();

Playground

Kaplan
  • 2,572
  • 13
  • 14