简体   繁体   中英

Java Convert Int to Hex and stick it in byte array element

I've started learning a little java, and am trying to accomplish what is likely a very simply task but I'm struggling with it.

Say I have a byte array:

byte[] test = {(byte) 0x0a, (byte) 0x01, (byte) 0x01, (byte) 0x0b};

and I want to change test[3], the last value which is currently the number 11 (0b), to something random.

Random generator = new Random();

int newTest3 = generator.nextInt(255);

So, now I have some random number in newTest3. I want to convert this to hex (FF) and then place that into the last element of test, or test[3].

I couldn't find much to help me on this, and I literally just picked up java a couple hours ago, so any help would be outstanding!

Thanks in advance :)

I don't see why you go over so much trouble. Use explicit cast as you are already doing :) when you write:

byte[] test = {(byte) 0x0a, (byte) 0x01, (byte) 0x01, (byte) 0x0b};

0x0a is actually an int which you explicitly cast to a byte. You could do the same with newTest3.

test[3] = (byte)  newTest3;

Notice that this kind of cast usually involve loss of data since byte is just 8bits and int is 32bits. so for example (FFFFFFFF would be cast to FF).

Use a byte buffer

// elsewhere
import java.nio.ByteBuffer;

byte[] arr = new byte[4];
ByteBuffer buf = ByteBuffer.wrap(arr);
buf.putInt(generator.nextInt(255);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM