-
Notifications
You must be signed in to change notification settings - Fork 231
Conversation
Properly convert bytes to unsigned integers
Codecov Report
@@ Coverage Diff @@
## master #199 +/- ##
=========================================
Coverage 81.34% 81.34%
Complexity 470 470
=========================================
Files 77 77
Lines 1812 1812
Branches 214 214
=========================================
Hits 1474 1474
Misses 249 249
Partials 89 89
Continue to review full report at Codecov.
|
@@ -50,7 +50,7 @@ public static int ipToInt(String ip) throws EmptyIpException, NotFourOctetsExcep | |||
|
|||
int intIp = 0; | |||
for (byte octet : octets.getAddress()) { | |||
intIp = (intIp << 8) | (octet); | |||
intIp = (intIp << 8) | (octet & 0xFF); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
for my education, since octet
is already of type byte
, why does & 0xFF
make a difference?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
octet
is promoted to integer via binary numeric promotion (https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2), but it's a signed integer so the mask is filled with 1s on the left for negative numbers. & 0xFF
converts it to unsigned (It's a byte so no need to care about int overflow. If it mattered then it should be 0xFFL
). At least that's how I understand that.
In Java 8 that would instead be: Byte.toUnsignedInt(octet)
|
||
@Test | ||
public void testIpToInt32_above127() { | ||
int expectedIp = 176750850; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the magic number is hard to validate, how about a sanity check
assertEquals(expectedIp, (10 << 24) | (137 << 16) | (1 << 8) | 2); // sanity check
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Makes sense. I've also changed assertions to assertThat(x, equals(y))
, I think that they are more readable
Thanks! |
Properly convert bytes to unsigned integers
Fixes #198