Rust中是否有任何东西可以将二进制字符串转换为整数? [英] Is there anything in Rust to convert a binary string to an integer?

查看:509
本文介绍了Rust中是否有任何东西可以将二进制字符串转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的二进制文件现在以字符串形式驻留,我希望将其format!用作整数,就像我将整数格式化为二进制文件一样:format!("{:b}", number).

My binary resides as a string right now, I was hoping to format! it as an integer the same way I formatted my integer to binary: format!("{:b}", number).

我有一个较大的二进制字符串,我要在循环中取出切片,所以我们假设我的切片之一是:

I have a larger string of binary that I'm taking slices out of in a loop, so let's assume one of my slices is:

let bin_idx: &str = "01110011001";

我想将该二进制文件格式化为整数:

I want to format that binary into an integer:

format!("{:i}", bin_idx);

这会导致编译器错误:

error: unknown format trait `i`
 --> src/main.rs:3:21
  |
3 |     format!("{:i}", bin_idx);
  |                     ^^^^^^^

我还尝试了 du 并出现相同的错误.

I also tried d and u and got the same error.

推荐答案

首先,您应该使用

First of all, you should be using the official docs; those you pointed to are way outdated.

您有一个字符串,并且不能将字符串格式化为整数.我认为您想要的是一个解析器.这是使用from_str_radix的版本:

You have a string and you can't format a string as an integer. I think what you want is a parser. Here's a version using from_str_radix:

fn main() {
    let bin_idx = "01110011001";
    let intval = isize::from_str_radix(bin_idx, 2).unwrap();
    println!("{}", intval);
}

(游乐场)

这篇关于Rust中是否有任何东西可以将二进制字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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