How to read bigend data from tcpstream

How does TcpStream explicitly specify the byte order written or written by the writer?

just like this:


endianess only make sense for types consists of multiple bytes, like u16, i32, etc, write_all() takes a byte slices (&[u8]) as argument, and endianess is meaningless for byte slices because they represent raw bytes.

instead, you should specify the endianess when you serialize your data into raw bytes. there's plenty ways you can do this. for primitive scalar types, you can just use the builtin conversion functions like i32::to_be_bytes(). for custom types, you can either write the conversion yourself, or use crates like byteorder and the like.


Check out the byteorder crate.

use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt};

let mut rdr = Cursor::new(vec![2, 5, 3, 0]);
// Note that we use type parameters to indicate which kind of byte order
// we want!
assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap());
assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap());
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.