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?

Kenny
  • 1,110
  • 3
  • 13
  • 42
  • Possible duplicate of http://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java –  Jan 03 '15 at 19:28
  • And what do you mean by "encoding" for an *`int`*? Usually you only need encoding for a string. –  Jan 03 '15 at 19:31
  • So, you want to convert the length to its hexadecimal representation? – Phantômaxx Jan 03 '15 at 19:32
  • @dudeprgm That makes sense, sorry! – Kenny Jan 03 '15 at 19:35
  • "...converting it to 0x05" Converting _what_ to 0x05? The length of the given string? What is 0x05? Do you mean the _String_ "0x05"? Does the x mean hexadecimal? What if the length was a much larger number? What are the constraints on the length and format of the string? – Solomon Slow Jan 03 '15 at 19:40
  • 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](http://en.wikipedia.org/wiki/Endianness) which are commonly used for fixed width integral types, and then there are [*varint* encodings](https://developers.google.com/protocol-buffers/docs/encoding#varints) which use a variable number of bytes per integer. – Mike Samuel Jan 03 '15 at 19:40
  • @MikeSamuel Ah, sorry. I just thought that when he was referring to a specific encoding, he was referring to String encodings, like UTF-8, etc. (From his comment, apparently he was but nevertheless, sorry for the mistake.) –  Jan 03 '15 at 19:47

1 Answers1

1

Try the ByteBuffer class...

byte[] byteArray = ByteBuffer.allocate(1).putInt(username.length()).array();
Todd
  • 30,472
  • 11
  • 81
  • 89
  • java.nio.BufferOverflowException is called. I'm doing something wrong? – Kenny Jan 03 '15 at 20:13
  • 1
    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. – Todd Jan 03 '15 at 20:16
  • 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. – Kenny Jan 03 '15 at 20:38
  • 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. – Todd Jan 04 '15 at 00:06
  • Thanks again. Got it working. Yeah, I was lost and didn't know how to explain it. – Kenny Jan 04 '15 at 00:28