-4

I am trying to convert an integer to byte literal in Rust:

for x in 0..10000 {
  let key = x.to_???;
  other_function(key);
}

Could not find it in the docs.

Istvan
  • 7,500
  • 9
  • 59
  • 109
  • 2
    "byte literal" is not a type, you most likely mean `u8`. Also, how do you expect to convert `10000` to a byte? – mcarton Apr 25 '19 at 17:22
  • 1
    I suspect you want to convert the integer to `&[u8]` or `[u8; n]` in either big endian or little endian byte order, but without further information it's impossible to tell. – Sven Marnach Apr 25 '19 at 17:57
  • Thanks for clarifying. – Istvan Apr 25 '19 at 21:07

1 Answers1

5

A byte literal is something like b'f', a literal value written down. You probably mean a byte, which is usually a u8, sometimes an i8. You can use the TryFrom-trait on recent rust:

use std::convert::TryFrom;

fn main() {
    for i in 253..257 {
        let u = u8::try_from(i).expect("Not all integers can be represented via u8");
        println!("{}", u);
    }
}

u inside the loop is an u8. The code will print 253, 254, 255 and crash on the iteration where i becomes larger than what a u8 can represent.

mcarton
  • 27,633
  • 5
  • 85
  • 95
user2722968
  • 13,636
  • 2
  • 46
  • 67