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