2

I have the following values:

public static short TAG_VALUE1 = 0x2E09;
public static short TAG_VALUE2 = 0x2E0D;

And I want to create a byte[] from both values. As a byte array, I have to get the first byte and insert it into the array and then the second byte of each TAG. I tried to convert to string and then go back, but I think it has to be an easier way to do so.

How can I get this in a byte[] that looks like this?

2E 09 2E 0D

3
  • 1
    Use bit masks and byte shifts (sorry no time to elaborate). Commented Jul 28, 2015 at 14:52
  • You need to use bitwise operations to shift the bytes from the short into the byte array: see: en.wikipedia.org/wiki/Bitwise_operation for examples of bitwise operations.. Commented Jul 28, 2015 at 14:52
  • Do you have some code? Commented Jul 28, 2015 at 14:56

2 Answers 2

4

How about

byte[] foo = new byte[] {
    (byte) (TAG_VALUE1>>8),
    (byte) (TAG_VALUE1),
    (byte) (TAG_VALUE2>>8),
    (byte) (TAG_VALUE2),
};
Sign up to request clarification or add additional context in comments.

2 Comments

This looks really nice! I tried your code, and it's doing exactly what I asked in a simple way. But when I recover the data, it stores the decimal value of each byte instead of the hexadecimal value of each byte. Any idea?
The value is the same, what you mean is that Java by default uses the decimal representation of the value when displaying it. If you want to display the hexadecimal values, do this: for (byte b : foo) { System.out.println (String.format("%02x", b)); }
2

See ByteBuffer and its many uses.

byte[] bytes = new byte[4];
ByteBuffer buf = ByteBuffer.wrap(bytes);
buf.putShort(TAG_VALUE1);
buf.putShort(TAG_VALUE2);

Comments

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.