0

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?

7
  • Possible duplicate of stackoverflow.com/questions/1936857/… Commented Jan 3, 2015 at 19:28
  • And what do you mean by "encoding" for an int? Usually you only need encoding for a string. Commented Jan 3, 2015 at 19:31
  • So, you want to convert the length to its hexadecimal representation? Commented Jan 3, 2015 at 19:32
  • @dudeprgm That makes sense, sorry! Commented Jan 3, 2015 at 19:35
  • 1
    @dudeprgm, No. Integers are a datatype like any other that needs to be encoded when serialized or laid out in memory. There are two different endiannesses which are commonly used for fixed width integral types, and then there are varint encodings which use a variable number of bytes per integer. Commented Jan 3, 2015 at 19:40

1 Answer 1

1

Try the ByteBuffer class...

byte[] byteArray = ByteBuffer.allocate(1).putInt(username.length()).array();
Sign up to request clarification or add additional context in comments.

5 Comments

java.nio.BufferOverflowException is called. I'm doing something wrong?
Ah, sorry, that call to 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.
Thanks. But this represents the size of the string with just bytes? I need to write the size of the string on the header of packet with only two bytes.
If you only need two bytes and you know your String won't be larger than that, you can either deal in shorts (.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.
Thanks again. Got it working. Yeah, I was lost and didn't know how to explain it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.