short,int,long与byte数组之间的转换

2008-01-03 14:52:54.0     推荐:0    收藏:0    评论:0     来源:e800Java频道


我们如果多了解一些底层东西,对开发程序是很有帮助的.
我把java.nio.Bits中的代码正理了一下:

package com.test;

import java.nio.ByteBuffer;

public class ByteUtil {

/**
* @param args
*/
public static void main(String[] args) {
short s = -20;
byte[] b = new byte[2];
putShort(b, s, 0);
ByteBuffer buf = ByteBuffer.allocate(2);
buf.put(b);
buf.flip();
System.out.println(getShort(b, 0));
System.out.println(buf.getShort());
System.out.println("***************************");
int i = -40;
b = new byte[4];
putInt(b, i, 0);
buf = ByteBuffer.allocate(4);
buf.put(b);
buf.flip();
System.out.println(getInt(b, 0));
System.out.println(buf.getInt());
System.out.println("***************************");
long l = -40;
b = new byte[8];
putLong(b, l, 0);
buf = ByteBuffer.allocate(8);
buf.put(b);
buf.flip();
System.out.println(getLong(b, 0));
System.out.println(buf.getLong());
System.out.println("***************************");
}

public static void putShort(byte b[], short s, int index) {
b[index] = (byte) (s >> 8);
b[index + 1] = (byte) (s >> 0);
}

public static short getShort(byte[] b, int index) {
return (short) (((b[index] << 8) | b[index + 1] & 0xff));
}

// ///////////////////////////////////////////////////////
public static void putInt(byte[] bb, int x, int index) {
bb[index + 0] = (byte) (x >> 24);
bb[index + 1] = (byte) (x >> 16);
bb[index + 2] = (byte) (x >> 8);
bb[index + 3] = (byte) (x >> 0);
}

public static int getInt(byte[] bb, int index) {
return (int) ((((bb[index + 0] & 0xff) << 24)
| ((bb[index + 1] & 0xff) << 16)
| ((bb[index + 2] & 0xff) << 8) | ((bb[index + 3] & 0xff) << 0)));
}

// /////////////////////////////////////////////////////////
public static void putLong(byte[] bb, long x, int index) {
bb[index + 0] = (byte) (x >> 56);
bb[index + 1] = (byte) (x >> 48);
bb[index + 2] = (byte) (x >> 40);
bb[index + 3] = (byte) (x >> 32);
bb[index + 4] = (byte) (x >> 24);
bb[index + 5] = (byte) (x >> 16);
bb[index + 6] = (byte) (x >> 8);
bb[index + 7] = (byte) (x >> 0);
}

public static long getLong(byte[] bb, int index) {
return ((((long) bb[index + 0] & 0xff) << 56)
| (((long) bb[index + 1] & 0xff) << 48)
| (((long) bb[index + 2] & 0xff) << 40)
| (((long) bb[index + 3] & 0xff) << 32)
| (((long) bb[index + 4] & 0xff) << 24)
| (((long) bb[index + 5] & 0xff) << 16)
| (((long) bb[index + 6] & 0xff) << 8) | (((long) bb[index + 7] & 0xff) << 0));
}
}

您可以针对本文进行:[评论]  [收藏]  [推荐]  
  • 共有0条评论  点击查看更多评论
  • 网友评论仅供网友表达个人看法,并不表明e800同意其观点或证实其描述
我想发表评论:
用户名密码
  • 匿名发表
    验证码: