Emanuel
Emanuel

Reputation: 67

How to read hex from file

I want to read some data from a file in order to xor this with another sequence. The content of the file is

00112233445566778899aabbccddeeff

The sequence this should be xored with is

000102030405060708090a0b0c0d0e0f

The result should be:

00102030405060708090a0b0c0d0e0f0

The reason why i get a differnt result is that rust reads the content as ascii, like this:

buffer: [48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55]
buffer: [56, 56, 57, 57, 97, 97, 98, 98, 99, 99, 100, 100, 101, 101, 102, 102]

Is there a way to read the content directly to an hex array or how would one convert this?

Upvotes: 0

Views: 2573

Answers (2)

Emanuel
Emanuel

Reputation: 67

This does the job, reads 16 byte blocks until the end of the file, converts it to &str and converts it again into a vector of Chars:

let mut buffer = [0;16];

    while let Ok(n) = file.read(&mut buffer) {
        if n == 0 {
            break;
        }

        let s = match str::from_utf8(&buffer) {
            Ok(str) => str,
            Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
        };

        let mut content = s.to_string();
        let char_vec: Vec<char> = content.chars().collect();
        println!("Chars{:?}", char_vec);
    }

Upvotes: -1

sbnair
sbnair

Reputation: 11

You can use hex::decode to convert hex into bytes and then use '^' symbol to do xor operation with bits to get your result.

Upvotes: 0

Related Questions