Everything in Java binary format files is stored big-endian, MSB(Most Significant Byte) first. This is sometimes called network order. This is good news. This means if you use only Java, all files are done the same way on all platforms Mac, PC, Solaris, etc. You can freely exchange binary data electronically over the Internet or on floppy without any concerns about endianness. short readShortLittleEndian( )
{
// 2 bytes
int low = readByte() & 0xff;
int high = readByte() & 0xff;
return (short )(high << 8 | low);
}
long readLongLittleEndian( )
{
// 8 bytes
long accum = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy+ =8 )
{
// must cast to long or shift done modulo 32
accum |= ( long)(readByte () & 0xff) << shiftBy;
}
return accum;
}
double readDoubleLittleEndian( )
{
long accum = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy+ =8 )
{
// must cast to long or shift done modulo 32
accum |= ( (long)(readByte() & 0xff)) << shiftBy;
}
return Double.longBitsToDouble (accum);
}
float readFloatLittleEndian( )
{
int accum = 0;
for ( int shiftBy = 0; shiftBy < 32; shiftBy+ =8 )
{
accum |= (readByte () & 0xff) << shiftBy;
}
return Float.intBitsToFloat (accum);
}
或者考虑 JDK1.4
Java 1.4
In Java 1.4 (in beta as of 2001 August), you can do things like this to deal with little endian data:
float f = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getFloat();
{
// 2 bytes
int low = readByte() & 0xff;
int high = readByte() & 0xff;
return (short )(high << 8 | low);
}
long readLongLittleEndian( )
{
// 8 bytes
long accum = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy+ =8 )
{
// must cast to long or shift done modulo 32
accum |= ( long)(readByte () & 0xff) << shiftBy;
}
return accum;
}
double readDoubleLittleEndian( )
{
long accum = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy+ =8 )
{
// must cast to long or shift done modulo 32
accum |= ( (long)(readByte() & 0xff)) << shiftBy;
}
return Double.longBitsToDouble (accum);
}
float readFloatLittleEndian( )
{
int accum = 0;
for ( int shiftBy = 0; shiftBy < 32; shiftBy+ =8 )
{
accum |= (readByte () & 0xff) << shiftBy;
}
return Float.intBitsToFloat (accum);
}
或者考虑 JDK1.4
Java 1.4
In Java 1.4 (in beta as of 2001 August), you can do things like this to deal with little endian data:
float f = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getFloat();
public static String toHEXString(byte b)
{
return (""+"0123456789ABCDEF".charAt(0xf&b>>4)+"0123456789ABCDEF".charAt(b&0xF));
}
你这样没有根本上解决问题。我的所有数据都要这么读出来,而且还要进行运算。也就是不仅仅是一个显示的问题,而是实际就要用的问题。因为人家给我的都是在vc下用非流的形式写进去的,我现在却用流的形式读出来,这里不统一了。simoncn(早睡早起精神好)可能有一种好的方法,可我看不东,而且他写的函数编译也不通过。
请大家帮忙,我很急。
java规定的字节序是高位在前。
但用c写程序时,在不同的cpu和不同的操作系统上,字节序是不同的。