Skip to content

Instantly share code, notes, and snippets.

@carsontang
Created February 5, 2017 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carsontang/8d7c7680e84a509545a6b259de8098ff to your computer and use it in GitHub Desktop.
Save carsontang/8d7c7680e84a509545a6b259de8098ff to your computer and use it in GitHub Desktop.
Description to Thrift Binary Protocol wrapped around Thrift Transport
/**
The following method comes directly from Apache Thrift's TBinaryProtocol.java.
According to the Thrift whitepaper[0], a i32 is a 32-bit signed integer.
In Java, the primitive type, int, is also a 32-bit signed integer, so Java
represents i32 with int. [1]
The following is a 32-bit (4-byte) integer:
MSB LSB
0x?? 0x?? 0x?? 0x??
byte1 byte2 byte3 byte4
MSB = most significant byte
LSB = least significant byte
Thrift separates protocols from the transport layer. You can think of
the transport layer as the "thing" you're reading from and/or writing to.
Okay, so why can't a computer just write to the transport,
and a computer on the other end just read from the transport?
Some computers store integers and objects in Big Endian form, and
others store them in Little Endian form. So when computers communicate,
they must communicate with a protocol to know when they start and finish
"speaking" to each other, and in what format to understand the bytes.
In the method below, the MSB is the first element of the byte array,
of size 4 bytes. The LSB is the last element of the byte array.
[0] http://thrift.apache.org/static/files/thrift-20070401.pdf
[1] https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
*/
private byte[] i32out = new byte[4];
public void writeI32(int i32) throws TException {
i32out[0] = (byte)(0xff & (i32 >> 24));
i32out[1] = (byte)(0xff & (i32 >> 16));
i32out[2] = (byte)(0xff & (i32 >> 8));
i32out[3] = (byte)(0xff & (i32));
trans_.write(i32out, 0, 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment