How to do it...

Follow these steps:

  1. Open the Cargo.toml file that was generated earlier for you.

  2. Under [dependencies], add the following line:
byteorder = "1.1.0"
  1. If you want, you can go to byteorder's crates.io page (https://crates.io/crates/byteorder) to check for the newest version and use that one instead.
  2. In the bin folder, create a file called bytes.rs.

  3. Add the following code and run it with cargo run --bin bytes:

1    extern crate byteorder;
2 use std::io::{Cursor, Seek, SeekFrom};
3 use byteorder::{BigEndian, LittleEndian, ReadBytesExt,
WriteBytesExt};
4
5 fn main() {
6 let binary_nums = vec![2, 3, 12, 8, 5, 0];
7 // Wrap a binary collection in a cursor
8 // to provide seek functionality
9 let mut buff = Cursor::new(binary_nums);
10 let first_byte = buff.read_u8().expect("Failed to read
byte");
11 println!("first byte in binary: {:b}", first_byte);
12
13 // Reading advances the internal position,
14 // so now we read the second
15 let second_byte_as_int = buff.read_i8().expect("Failed to
read byte as int");
16 println!("second byte as int: {}", second_byte_as_int);
17
18 // Overwrite the current position
19 println!("Before: {:?}", buff);
20 buff.write_u8(123).expect("Failed to overwrite a byte");
21 println!("After: {:?}", buff);
22
23
24 // Set and get the current position
25 println!("Old position: {}", buff.position());
26 buff.set_position(0);
27 println!("New position: {}", buff.position());
28
29 // This also works using the Seek API
30 buff.seek(SeekFrom::End(0)).expect("Failed to seek end");
31 println!("Last position: {}", buff.position());
32
33 // Read and write in specific endianness
34 buff.set_position(0);
35 let as_u32 = buff.read_u32::<LittleEndian>()
36 .expect("Failed to read bytes");
37 println!(
38 "First four bytes as u32 in little endian order: {}",
39 as_u32
40 );
41
42 buff.set_position(0);
43 let as_u32 = buff.read_u32::<BigEndian>().expect("Failed to
read bytes");
44 println!("First four bytes as u32 in big endian order: {}",
as_u32);
45
46 println!("Before appending: {:?}", buff);
47 buff.seek(SeekFrom::End(0)).expect("Failed to seek end");
48 buff.write_f32::<LittleEndian>(-33.4)
49 .expect("Failed to write to end");
50 println!("After appending: {:?}", buff);
51
52 // Read a sequence of bytes into another buffer
53 let mut read_buffer = [0; 5];
54 buff.set_position(0);
55 buff.read_u16_into::<LittleEndian>(&mut read_buffer)
56 .expect("Failed to read all bytes");
57 println!(
58 "All bytes as u16s in little endian order: {:?}",
59 read_buffer
60 );
61 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.151.107