如何在Rust中将字符串转换为十六进制? [英] How do I convert a string to hex in Rust?

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

问题描述

我想在Rust中将字符串(SHA256哈希)转换为十六进制:

I want to convert a string of characters (a SHA256 hash) to hex in Rust:

extern crate crypto;
extern crate rustc_serialize;

use rustc_serialize::hex::ToHex;
use crypto::digest::Digest;
use crypto::sha2::Sha256;

fn gen_sha256(hashme: &str) -> String {
    let mut sh = Sha256::new();
    sh.input_str(hashme);

    sh.result_str()
}

fn main() {
    let hash = gen_sha256("example");

    hash.to_hex()
}

编译器说:

error[E0599]: no method named `to_hex` found for type `std::string::String` in the current scope
  --> src/main.rs:18:10
   |
18 |     hash.to_hex()
   |          ^^^^^^

我可以看到这是真的;看起来像它仅适用于[u8] .

I can see this is true; it looks like it's only implemented for [u8].

我该怎么办?在Rust中,是否没有实现从字符串转换为十六进制的方法?

What am I to do? Is there no method implemented to convert from a string to hex in Rust?

我的Cargo.toml依赖项:

My Cargo.toml dependencies:

[dependencies]
rust-crypto = "0.2.36"
rustc-serialize = "0.3.24"


编辑我刚刚意识到rust-crypto库中的字符串已经以十六进制格式已经.天啊


edit I just realized the string is already in hex format from the rust-crypto library. D'oh.

推荐答案

我将在这里四肢走动,并建议解决方案将hash设置为Vec<u8>类型.

I will go out on a limb here, and suggest that the solution is for hash to be of type Vec<u8>.

问题是,尽管确实可以使用as_bytesString转换为&[u8],然后使用to_hex,但首先需要具有一个有效的String对象.

The issue is that while you can indeed convert a String to a &[u8] using as_bytes and then use to_hex, you first need to have a valid String object to start with.

虽然任何String对象都可以转换为&[u8],但反之则不成立. String对象仅用于保存有效的UTF-8编码的Unicode字符串:并非所有字节模式都符合条件.

While any String object can be converted to a &[u8], the reverse is not true. A String object is solely meant to hold a valid UTF-8 encoded Unicode string: not all bytes pattern qualify.

因此,gen_sha256生成String是不正确的.更正确的类型是Vec<u8>,它实际上可以接受任何字节模式.从那时起,调用to_hex很简单:

Therefore, it is incorrect for gen_sha256 to produce a String. A more correct type would be Vec<u8> which can, indeed, accept any bytes pattern. And from then on, invoking to_hex is easy enough:

hash.as_slice().to_hex()

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

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