如何将 Base64 字符串转换为十六进制字符串?

问题描述 投票:0回答:1

如何使用 Rust 将 Base64 字符串转换为十六进制字符串?

rust base64 hex
1个回答
0
投票

这是一个受 https://stackoverflow.com/a/44532957 和 base64 文档启发的实现。

extern crate base64;
use std::u8;
use base64::{Engine as _, alphabet, engine::{self, general_purpose}};

pub fn base64_to_hex(base64: String) -> String {
    let mut buffer = Vec::<u8>::new();
    general_purpose::STANDARD.decode_vec(base64, &mut buffer,).unwrap();
    // Convert to hex thanks to https://stackoverflow.com/a/73358987
    return buffer.iter()
    .map(|b| format!("{:02x}", b).to_string())
    .collect::<Vec<String>>()
    .join("");
}

fn main() {
    print!("{}", base64_to_hex("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t".to_string()));
    // Outputs 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
}
© www.soinside.com 2019 - 2024. All rights reserved.