Kenny
Kenny

Reputation: 1142

Convert int to byte array

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?

Upvotes: 0

Views: 201

Answers (1)

Todd
Todd

Reputation: 31700

Try the ByteBuffer class...

byte[] byteArray = ByteBuffer.allocate(1).putInt(username.length()).array();

Upvotes: 1

Related Questions