十进制数转十六进制字符串 [英] Decimal number to hexadecimal string

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

问题描述

Rust 是否有一组函数可以轻松地将十进制整数转换为十六进制字符串?我可以轻松地将字符串转换为整数,但我似乎无法弄清楚相反的情况.目前我所拥有的不起作用(可能有点令人厌恶)

Does Rust have a set of functions that make converting a decimal integer to a hexadecimal string easy? I have no trouble converting a string to an integer, but I can't seem to figure out the opposite. Currently what I have does not work (and may be a bit of an abomination)

编者注 - 此代码早于 Rust 1.0,不再编译.

Editor's note - this code predates Rust 1.0 and no longer compiles.

pub fn dec_to_hex_str(num: uint) -> String {
    let mut result_string = String::from_str("");
    let mut i = num;
    while i / 16 > 0 {
        result_string.push_str(String::from_char(1, from_digit(i / 16, 16).unwrap()).as_slice());
        i = i / 16;
    }
    result_string.push_str(String::from_char(1, from_digit(255 - i * 16, 16).unwrap()).as_slice());

    result_string
}

我是在正确的轨道上,还是我想多了?

Am I on the right track, or am I overthinking this whole thing?

推荐答案

你想得太多了.

assert_eq!(format!("{:x}", 42), "2a");
assert_eq!(format!("{:X}", 42), "2A");

来自 std::fmt::LowerHexstd::fmt::UpperHex,分别.另请参阅搜索hex"文档.

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

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