Skip to content

Commit 6bc05de

Browse files
committed
Applying Hiroshi's test from IO-117 with my fix. Fixes negative number possibilities in EndianUtils.readSwappedUnsignedInteger()
git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/io/trunk@539632 13f79535-47bb-0310-9956-ffa450edef68
1 parent 6633728 commit 6bc05de

2 files changed

Lines changed: 27 additions & 8 deletions

File tree

src/java/org/apache/commons/io/EndianUtils.java

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -182,10 +182,13 @@ public static int readSwappedInteger(byte[] data, int offset) {
182182
* @return the value read
183183
*/
184184
public static long readSwappedUnsignedInteger(byte[] data, int offset) {
185-
return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
186-
( ( data[ offset + 1 ] & 0xff ) << 8 ) +
187-
( ( data[ offset + 2 ] & 0xff ) << 16 ) +
188-
( ( data[ offset + 3 ] & 0xff ) << 24 ) );
185+
long low = ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
186+
( ( data[ offset + 1 ] & 0xff ) << 8 ) +
187+
( ( data[ offset + 2 ] & 0xff ) << 16 ) );
188+
189+
long high = data[ offset + 3 ] & 0xff;
190+
191+
return (high << 24) + (0xffffffffL & low);
189192
}
190193

191194
/**
@@ -368,10 +371,13 @@ public static long readSwappedUnsignedInteger(InputStream input)
368371
int value3 = read( input );
369372
int value4 = read( input );
370373

371-
return ( ( value1 & 0xff ) << 0 ) +
372-
( ( value2 & 0xff ) << 8 ) +
373-
( ( value3 & 0xff ) << 16 ) +
374-
( ( value4 & 0xff ) << 24 );
374+
long low = ( ( ( value1 & 0xff ) << 0 ) +
375+
( ( value2 & 0xff ) << 8 ) +
376+
( ( value3 & 0xff ) << 16 ) );
377+
378+
long high = value4 & 0xff;
379+
380+
return (high << 24) + (0xffffffffL & low);
375381
}
376382

377383
/**

src/test/org/apache/commons/io/EndianUtilsTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,4 +263,17 @@ public void testSymmetryOfLong() throws IOException {
263263
}
264264
}
265265

266+
// tests #IO-117
267+
public void testUnsignedOverrun() throws Exception {
268+
byte[] target = new byte[] { 0, 0, 0, (byte)0x80 };
269+
long expected = 0x80000000L;
270+
271+
long actual = EndianUtils.readSwappedUnsignedInteger(target, 0);
272+
assertEquals("readSwappedUnsignedInteger(byte[], int) was incorrect", expected, actual);
273+
274+
ByteArrayInputStream in = new ByteArrayInputStream(target);
275+
actual = EndianUtils.readSwappedUnsignedInteger(in);
276+
assertEquals("readSwappedUnsignedInteger(InputStream) was incorrect", expected, actual);
277+
}
278+
266279
}

0 commit comments

Comments
 (0)