Wednesday, June 17, 2015

Android: Handling ByteBuffer

In case you are given a structured byteBuffer and you have to cipher the contents of it, here's a quick start up walk through to it.

 //To get relative positioning variables
 short version = byteBufferData.getShort();
 //Besides for getShort(), there's getInt(), getLong(),
 //getDouble(), getChar(). getFloat()
 //Or you can use the following to indicate the 
 //position you want to start to read from
 //short shortVar = byteBufferData.getShort(0);
 //but if you use getShort() without any parameters, 
 //it will increase the current position of the 
 //byteBuffer too. Depending on the function used,
 //the position will be increase differently.
 //E.g. getChar(), getShort(), increases by 2
 //getInt(), getFloat(), increases by 4
 //getDouble, getLong(), increases by 8
 //But what if there's a String of a certain length?
 //For example, you know that the length of the string
 //will be 5. You would need to create the corresponding
 //byte Array first
 final byte[] bytes = new byte[5];
 //then you will get the byte Array that matches the length
 //then you can pass the byte Array into a String and Voila!!!
 //there you go, a String pulled out from the ByteBuffer
 String filename = new String(bytes);

 //You can use the same steps in the above to control/store
 //binary data for other types of Object too. :)
* Click here to find about the different functions and properties of the 'ByteBuffer' class in

No comments:

Post a Comment