gpt4 book ai didi

rust - 在 Rust 中将二进制字符串转换为带有前导零的十六进制字符串

转载 作者:行者123 更新时间:2023-11-29 07:57:05 24 4
gpt4 key购买 nike

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.

肯定有比这更好的将二进制字符串转换为十六进制字符串的方法吗?

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);
}

结果是

Bin: 0001111
Hex: 00000078 @ 4 bytes

我正在使用 rustc 0.12.0-nightly

最佳答案

有一种方法可以用 std::u32::from_str_radix 以更简洁的形式做你想做的事和 format!宏观:

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可能有点晦涩,但 01$x 本质上意味着该数字必须以十六进制形式打印,并用零填充到作为第二个(第一个基于零的索引)参数传递的长度。

关于rust - 在 Rust 中将二进制字符串转换为带有前导零的十六进制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26285550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com