2

Is it possible?

I am trying to conver a string to a 4byte array.

I saw a way of doing so with integer:

int i =55555;
ByteBuffer.allocate(4).putInt(i).array();

Cant find a way with String.

2
  • 1
    "Is it possible?" In general no. Only short strings can be represented in 4 bytes. It depends on the character set and on the encoding which strings can be represented. Commented Oct 1, 2013 at 8:55
  • By "converting a string to a four byte array", are you talking about something along the lines of taking the first four ASCII characters (or two Unicode characters) and converting them to their byte counterparts? Commented Oct 1, 2013 at 8:55

1 Answer 1

4

Whats wrong with "5555".getBytes();

or if you only want the first 4 bytes

"5555555".substring(0, 4).getBytes();

Sign up to request clarification or add additional context in comments.

3 Comments

Depends on how you want your bits representation using ByteBuffer is more appropriate for this task
Substring gets the first 4 chars (in whatever encoding), not bytes. Like this you could as well end up with 8 bytes.
Since this uses the default platform encoding, it will not always deliver 4 bytes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.