// // ByteSwapper class // part of the set of documents known as Java no sugar. // Copyright (c) 1996 Sunil Gupta, sunil@magnetic.demon.co.uk // placed into the public domain by the author // import java.io.*; public class ByteSwapper extends Object { public static long swapLong(long value) { long lhs, rhs; long answer; rhs = (long) swapInt( loInt(value)) ; lhs = (long) swapInt( hiInt(value)) ; answer = (rhs * 0x100000000l ) + lhs; return answer; } public static int swapInt(int value) { short lhs, rhs; rhs = swapShort( loWord(value)) ; lhs = swapShort( hiWord(value)) ; return (rhs * 0x10000) + lhs; } public static short swapShort(short value) { int lhs, rhs, answer; rhs = (int) loByte(value); lhs = (int) hiByte(value); answer = (rhs * 0x100) + lhs; return (short)answer; } public static int loInt(long value) { long answer; answer = value & 0xFFFFFFFFl; return ( (int) answer); } public static int hiInt(long value) { long answer; answer = value >>> 32; return ( (int) answer); } public static short loWord(int value) { return (short) (value & 0xFFFF); } public static short hiWord(int value) { return (short) ( value >>> 16); } public static byte loByte(short value) { return (byte) (value & 0xFF); } public static byte hiByte(short value) { return (byte) (value >>> 8); } //############################################################################ // TESTING //############################################################################ public static void main(String args[]) { int swapped; //***************** test short swapping ********************** swapped = swapShort((short)0x1234); if ( swapped == 0x3412 ) System.out.println ("short byteswapping code is fine"); else { System.out.println ( "short byteswapping code is b******d\n" + "\twanted: " + 0x3412 + "\n" + "\tgot : " + swapped ); } //***************** test int swapping ********************** swapped = swapInt(0x12345678); if ( swapped == 0x78563412 ) System.out.println ("int byteswapping code is fine"); else { System.out.println ( "short byteswapping code is b******d\n" + "\twanted: " + 0x78563412 + "\n" + "\tgot : " + swapped ); } } }
.