java 保存unsigned 数据方法

java中没有unsiged的设置,必须用signed的数据存储,也就是要多用些存储空间。
use a short to hold an unsigned byte, use a long to hold an unsigned int.
use a char to hold an unsigned short.
('char' type, which is a 2 byte representation of unicode, instead of the
C 'char' type, which is 1 byte ASCII. Java's 'char' also can be used as
an unsigned short, i.e. it represents numbers from 0 up to 2^16.)
从字节流中提取unsigned 数据,保存unsigned数据到字节流
    
      
short anUnsignedByte = 0 ;
char anUnsignedShort = 0 ;
long anUnsignedInt = 0 ;

int firstByte = 0 ;
int secondByte = 0 ;
int thirdByte = 0 ;
int fourthByte = 0 ;

byte buf[] = getMeSomeData();
// Check to make sure we have enough bytes
if (buf.length < ( 1 + 2 + 4 ))
doSomeErrorHandling();
int index = 0 ;

firstByte
= ( 0x000000FF & (( int )buf[index]))
index
++ ;
anUnsignedByte
= ( short )firstByte;

firstByte
= ( 0x000000FF & (( int )buf[index]))
secondByte
= ( 0x000000FF & (( int )buf[index + 1 ]))
index
= index + 2 ;
anUnsignedShort
= ( char ) (firstByte << 8 | secondByte);

firstByte
= ( 0x000000FF & (( int )buf[index]))
secondByte
= ( 0x000000FF & (( int )buf[index + 1 ]))
thirdByte
= ( 0x000000FF & (( int )buf[index + 2 ]))
fourthByte
= ( 0x000000FF & (( int )buf[index + 3 ]))
index
= index + 4 ;
anUnsignedInt
= (( long ) (firstByte << 24
| secondByte << 16
| thirdByte << 8
| fourthByte))
& 0xFFFFFFFFL ;
// write it back as unsigned int, unsigned short, unsigned byte.
buf[ 0 ] = (anUnsignedInt & 0xFF000000L ) >> 24 ;
buf[
1 ] = (anUnsignedInt & 0x00FF0000L ) >> 16 ;
buf[
2 ] = (anUnsignedInt & 0x0000FF00L ) >> 8 ;
buf[
3 ] = (anUnsignedInt & 0x000000FFL );

buf[
4 ] = (anUnsignedShort & 0xFF00 ) >> 8 ;
buf[
5 ] = (anUnsignedShort & 0x00FF );

buf[
6 ] = (anUnsignedByte & 0xFF );

你可能感兴趣的:(java)