How to determine a byte array beautifully by using if statements

Asked 2 years ago, Updated 2 years ago, 34 views

If all the values in the byte array are non-zero, I want to write a true if statement, but I can't write it smartly.
Below is an example implementation, but is there a smarter way to judge?
I look forward to your kind cooperation.

byte[] b={0x00,0x00,0x00,0x00};

if(b[0]!=0){
    if(b[1]!=0){
        if(b[2]!=0){
            if(b[3]!=0){
            /* Processing*/
            }
        }
    }
}

java

2022-09-30 20:24

4 Answers

 if(b[0]!=0&b[1]!=0&b[2]!=0&b[3]!=0)

That's all right.


2022-09-30 20:24

There were questions similar to , so I think these answers would be helpful.

One way to use the library is to be concise.

Google Guava:

//import com.google.common.primitives.Bytes;

if(!Bytes.contains(b,(byte)0)){
    /* Processing*/
}

Commons Lang:

//import org.apache.commons.lang3.ArrayUtils;

if(!ArrayUtils.contains(b,(byte)0)){
    /* Processing*/
}

Both implementations end up just looking at the elements of the array in the for loop, so it's easy to implement yourself (especially if you don't need versatility):

//How-to: if(!containsZero(b)){/*processing*/}

public static boolean contentsZero (final byte[]) array) {
    for (final byte b:array) {
        if(b==0){
            return true;
        }
    }
    return false;
}


2022-09-30 20:24

I don't know if it's smart, but

byte[] b={0x00,0x00,0x00,0x00};
byte checker=b[0]|b[1]|b[2]|b[3];

if(ckecker==0x00){
    // Processing when all bits are 0
}

How about ?


2022-09-30 20:24

If you use the contains series, it will work, but if you use byte, it won't work.

byte[] b={0x00,0x00,0x00,0x00};
        
boolean contains=Arrays.asList(b).contains(0x00);

if(contains){
  System.out.println("Hello");
} else{
  System.out.println("World");
}


2022-09-30 20:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.