在 Rust 中将二进制字符串转换为带有前导零的十六进制字符串 [英] Convert binary string to hex string with leading zeroes in Rust

查看:133
本文介绍了在 Rust 中将二进制字符串转换为带有前导零的十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编者注:此代码示例来自 Rust 1.0 之前的版本,在语法上不是有效的 Rust 1.0 代码.此代码的更新版本会产生不同的错误,但答案仍包含有价值的信息.

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

结果是

Bin: 0001111
Hex: 00000078 @ 4 bytes

我每晚使用 rustc 0.12.0

I'm using rustc 0.12.0-nightly

推荐答案

有一种方法可以用 std::u32::from_str_radixformat! 宏:

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
}

格式语法可能有点晦涩,但是01$x 本质上意味着数字必须以十六进制形式打印,并用零填充,直到作为第二个(第一个具有基于零的索引)参数传递的长度.

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.

这篇关于在 Rust 中将二进制字符串转换为带有前导零的十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆