I need a way to do this
String username = "Snake";
int usernameLength = username.length(); // 5
converting it to
0x05
Should I use a for loop to get each number and add a zero if the result is less than two numbers?
Try the ByteBuffer class...
byte[] byteArray = ByteBuffer.allocate(1).putInt(username.length()).array();
allocate(1) only allocates a single byte and you need at least 4 to call putInt(). My fault, sorry. Up that number to something larger and that should work..putShort((short)username.length())) and set the allocation to 2 (2 bytes). Or you can take the array() that gets returned and only use two bytes of it. None of this was clear at all in your question, by the way.
int? Usually you only need encoding for a string.