0

I am trying to covert a string to an ascii code in rust to turn the string into BrainFuck code:

(The variable "input" is the string "hello" and this snippet starts at line 12)

for x in input.chars(){
    ascii = x as u8;
    println!("{}", ascii);
    if ascii > 86 {
      target = ascii - 86;
      output = output.clone() + "+[--------->++++++<]>";
      for x in 0..target{
        output = output + "+";
      output = output + ".>";
      }
    
    }else if ascii <= 86 {
      println!("{}", ascii);
      target = ascii - 86;
      output = output.clone() + "+[--------->++++++<]>";
      for x in 0..target{
        output = output + "-";
      output = output + ".>"
      }
    }
  }
  println!("{}", output)

However, the program fails with an 'attempt to subtract with overflow' at 25:16. This was unusual so I printed out all of the ascii values and got:

104
101
108
108
111
10
10

I am not sure why the two extra 10's are there, but they seem to be causing this subtract overflow. Why are these 10's being put into the ascii varable? Could it be that I am technically converting a string to base 10 and rust puts them there by default?

12
  • 1
    You have two branches, one for ascii > 86 and one for ascii <= 86, but you have exactly the same code for either branch, including target = ascii - 86, which is certain to fail in the latter branch. Commented Mar 13, 2023 at 12:29
  • Copypasta strikes again! Good catch @SvenMarnach Commented Mar 13, 2023 at 12:30
  • There are more problems with the code, e.g. x as u8 will overflow if the input contains any Unicode codepoints ≥ 256. Commented Mar 13, 2023 at 12:31
  • The second if in the else branch is also unnecessary, and for iteratively building a string I recommend output.push_str(...) or write!(&mut output, ...). Commented Mar 13, 2023 at 12:33
  • 7
    The 10s are newline characters. Commented Mar 13, 2023 at 12:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.