如何在Rust中向矢量输入二进制值?

时间:2018-08-14 07:55:01

标签: binary rust

我已经编写了一个简单的ASCII到字符串转换器,但是在将其转换为二进制到字符串转换器时遇到了问题。

当我尝试输入二进制值时,我遇到了一个错误,向量插入跳过了输入中的起始零。

这是使用ASCII十进制值的代码:

library(shiny)

ui = fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput(inputId = "number", label = "number of selectInput",value = 5)
    ),
    mainPanel(
      column(
        width = 6,
        uiOutput(outputId = "putselect")
      ),
      column(
        width = 6,
        verbatimTextOutput(outputId = "text")
      )
    )
  )
)

server = function(input,output){
  output$putselect = renderUI(
    if(input$number >= 1){
      lapply(1:input$number, function(i){
        selectInput(inputId = paste0("input", i), label = paste("input", i), choices = c(2,(3)))
      })
    }
  )
  output$text <- renderText({
    if(input$number >= 1) {
      sum <- 0
      for(i in 1:input$number) {
        sum <- sum + as.numeric(input[[paste0("input", i)]])
      }
      return(sum)
    }
  })
}

shinyApp(ui = ui , server = server)

无效的代码:

use std::*;

fn main() {
    println!("AregevDev's binary to string converter!");
    println!("Enter a sequence of binary values:");

    let mut int_seq: Vec<u32> = Vec::new();

    loop {
        let mut it = String::new();
        io::stdin()
            .read_line(&mut it)
            .expect("Failed to read line!");
        let num = match it.trim().parse::<u32>() {
            Ok(num) => num,
            Err(_) => break,
        };

        int_seq.push(num);
    }

    println!("Converted string: {}", binary_to_string(&int_seq));
}

fn binary_to_string(vec: &Vec<u32>) -> String {
    let mut result = String::new();

    for u in vec.iter() {
        let ch = char::from_u32(*u).unwrap();
        result.push(ch);
    }

    return result;
}

错误:

use std::*;

fn main() {
    println!("AregevDev's binary to string converter!");
    println!("Enter a sequence of binary values:");

    let mut int_seq: Vec<u32> = Vec::new();

    loop {
        let mut it = String::new();
        io::stdin()
            .read_line(&mut it)
            .expect("Failed to read line!");
        let num = match it.trim().parse::<u32>() {
            Ok(num) => num,
            Err(_) => break,
        };

        int_seq.push(num);
    }

    println!("Vec: {:?}", int_seq);
    println!("Converted string: {:?}", binary_to_string(&int_seq));
}

fn binary_to_string(vec: &Vec<u32>) -> String {
    let mut result = String::new();

    for u in vec.iter() {
        let ch = char::from_digit(*u, 2).unwrap();
        result.push(ch);
    }

    return result;
}

1 个答案:

答案 0 :(得分:4)

与零相对应的字符在那里,但是您看不到它们:

fn main() {
    let mut s = String::new();
    s.push(char::from(0));
    s.push('a');
    s.push('b');
    println!("Hello, {}!", s);
    println!("{:?}", s);
    for c in s.chars() {
        println!("{}", c as u32);
    }
}

我无法向您显示输出,因为NUL字符也使Stack Overflow编辑器混乱。 :-)