I have a method to extract the most significant, non-zero byte in an integer using the following method:
private static int getFirstByte(int n)
{
while (n > 0xFF)
n >>= 8;
return n;
}
There’s a logic problem with this method. The integer parameter could be negative, which means it would return the number being passed in, which is incorrect.
There is also a possible issue with the method itself. It is using a while loop.
Is there a way to perform this logic without a while loop and also possibly avoiding the incorrectly returned result for negative numbers?
I assume by get the first non-zero
bytein anintyou mean natural 8 bit breaks of theintand not a dynamic 8 bit break.Natural 8 bit breaks:
00000000|00010110|10110010|11110001==>00010110Dynamic 8 bit break:
00000000000|10110101|1001011110001==>10110101This will return the first non-zero
byteon a natural 8-bit break of anintwithout looping or branching. This code may or may not be more efficient thenpaulsm4‘s answer. Be sure to do benchmarking and/or profiling of the code to determine which is best for you.Java Code:
ideone link