Deal with big-endian and little-endian order
From CodeCodex
Implementations[edit]
Java[edit]
Java virtual machine always used big-endian, Intel x86 used little-endian.
public class Swab { public final static int swabInt(int v) { return (v >>> 24) | (v << 24) | ((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00); } public static void main(String argv[]) { // before 0x01020304 // after 0x04030201 int v = 0x01020304; System.out.println("before : 0x" + Integer.toString(v,16)); System.out.println("after : 0x" + Integer.toString(swabInt(v),16)); } }
Ruby[edit]
def change_endian(input) output = 0 4.times do |i| input, r = input.divmod(256) output = output * 256 + r end output end before = 0x01020304 after = change_endian(before) printf "before : %#010x\n", before #=> before : 0x01020304 printf "after : %#010x\n", after #=> after : 0x04030201