The Source for Java Technology Collaboration
User: Password:



Start New Message Delete Post a Reply

Article: 
 (Not So) Stupid Questions 7: >>, >>>, <<, and ?: operators
Subject:  Crumb twiddling
Date:  2006-01-18 03:53:55
From:  tackline
Response to: power


That code doesn't do quite what it appears to. If inByte is negative, then the elements of the returned array will all be non-positive. Perhaps the method should only be called with values between 0 and 255 inclusive, in which case it should throw an IllegalArgumentException for exceptional cases when it is passed an illegal argument.

The problem is that both % and >> are signed operators. The semantics of % (and integer division) are rather arbitrary, so check the Java Language Spec (JLS) for the tedious details. Replacing either by unsigned equivalent operations would do. As 4 is a power of two, x%4 can be replaced with the bitwise expression x & 3, giving a non-negative result. x >> 2 can be replaced using the logical (rather than arithmetic) right shift operator, x >>> 2. The intent is more obvious if both expressions are replaced.

For code like this I would tend to write it as:

public static final int[] byteToLittleEndianCrumbs(int byteValue) {
    if (!(0 <= byteValue && byteValue <= 0x100)) {
        throw new IllegalArgumentException();
    }
    return new int[] {
        (byteValue >> 0) & 0xf,
        (byteValue >> 2) & 0xf,
        (byteValue >> 4) & 0xf,
        (byteValue >> 6) & 0xf,
    }
}

It is repetive, but in this case clearer than the loop.

Since Java 1.5, Integer and Long have gained a number of bit twiddling methods, along similar lines to these bitwise operators. IMO, the library would have been a better place for them all.












 Feed java.net RSS Feeds