Converting from byte to int in java

后端 未结 6 874
长发绾君心
长发绾君心 2020-12-02 09:53

I have generated a secure random number, and put its value into a byte. Here is my code.

SecureRandom ranGen = new SecureRandom();
byte[] rno = new byte[4];          


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 10:42

    if you want to combine the 4 bytes into a single int you need to do

    int i= (rno[0]<<24)&0xff000000|
           (rno[1]<<16)&0x00ff0000|
           (rno[2]<< 8)&0x0000ff00|
           (rno[3]<< 0)&0x000000ff;
    

    I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

    in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

    I also ensure any sign promotion won't affect the result with & 0xff

提交回复
热议问题