Reputation: 723
Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.
Surely there is a better way to convert binary string to hex string than this?
use std::num;
fn to_hex(val: &str, len: uint) {
println!("Bin: {}", val);
let mut int_val = 0i;
for (i,c) in val.chars().enumerate() {
if c == '1' {
int_val += num::pow(2i, i+1)/2;
}
}
let f32_val = int_val as f32;
let mut hex_val = std::f32::to_str_hex(f32_val).to_string();
while hex_val.len() != len*2 {
hex_val = "0".to_string() + hex_val;
}
println!("Hex: {} @ {} bytes", hex_val, len);
}
fn main() {
let value = "0001111";
to_hex(value,4);
}
The result for this is
Bin: 0001111
Hex: 00000078 @ 4 bytes
I'm using rustc 0.12.0-nightly
Upvotes: 7
Views: 9139
Reputation: 127811
There is a way to do what you want in a much terser form with std::u32::from_str_radix
and the format!
macro:
use std::u32;
fn to_hex(val: &str, len: usize) -> String {
let n: u32 = u32::from_str_radix(val, 2).unwrap();
format!("{:01$x}", n, len * 2)
}
fn main() {
println!("{}", to_hex("110011111111101010110010000100", 6))
// prints 000033feac84
}
The format syntax may be a little obscure, but 01$x
essentially means that the number must be printed in hexadecimal form padded with zeros up to the length passed as the second (1st with zero-based indexing) argument.
Upvotes: 13