java byte[]、int、long互转

2014-12-09 06:30:02 阅读( 577 )

2596人 收藏本页

标签:Java面试题

public class BinDataConvert {

public static void BinnCat( byte[] from, byte[] to, int offset, int len )
{
int max = offset + len;
int min = offset;
for( int i = min, j = 0; i < max; i++, j++ )
{
to = from[j];
}
}

public static byte[] LongToBin( long from, int len )
{
byte[] to = new byte[len];
int max = len;

for( int i_move = max – 1, i_to = 0; i_move >= 0; i_move–, i_to++ )
{
to[i_to] = (byte)( from >> ( 8 * i_move ) );
}

return to;
}
public static void LongToBin( long from, byte[] to, int offset, int len )
{
int max = len;
int min = offset;

for( int i_move = max – 1, i_to = min; i_move >= 0; i_move–, i_to++ )
{
to[i_to] = (byte)( from >> ( 8 * i_move ) );
}
}
public static byte[] IntToBin( int from, int len )
{
byte[] to = new byte[len];
int max = len;

for( int i_move = max – 1, i_to = 0; i_move >= 0; i_move–, i_to++ )
{
to[i_to] = (byte)( from >> ( 8 * i_move ) );
}

return to;
}
public static byte[] IntToBin( int from, byte[] to, int offset, int len )
{
int max = len;
int min = offset;

for( int i_move = max – 1, i_to = min; i_move >= 0; i_move–, i_to++ )
{
to[i_to] = (byte)( from >> ( 8 * i_move ) );
}

return to;
}

public static long BinToLong( byte[] from, int offset, int len )
{
long to;
int min = offset;
to = 0;
for( int i_move = len – 1, i_from = min; i_move >= 0; i_move–, i_from++ )
{
to = to << 8 | ( from[i_from] & 0xff );
}
return to;
}

public static int BinToInt( byte[] from, int offset, int len )
{
int to = 0;
int min = offset;
to = 0;

for( int i_move = len – 1, i_from = min; i_move >= 0; i_move–, i_from++ )
{
to = to << 8 | ( from[i_from] & 0xff );
}
return to;
}
}

来自IT公司面试手册

下一篇:Java对内存的管理是怎么运作的?

上一篇:java实现子线程全部结束主线程继续执行

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题