android byte[] 和short[]转换的方法代码
本文导语: 1,工具代码 代码如下:public class BytesTransUtil { private String TAG = "BytesTransUtil"; private static BytesTransUtil instance = null; private BytesTransUtil() { // Log.i(TAG, "instance BytesTransUtil"); } public static BytesTransUtil getInstance() { if (instance == null)...
1,工具代码
public class BytesTransUtil {
private String TAG = "BytesTransUtil";
private static BytesTransUtil instance = null;
private BytesTransUtil() {
// Log.i(TAG, "instance BytesTransUtil");
}
public static BytesTransUtil getInstance() {
if (instance == null) {
instance = new BytesTransUtil();
}
return instance;
}
public boolean testCPU() {
if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) {
// System.out.println("is big ending");
return true;
} else {
// System.out.println("is little ending");
return false;
}
}
public byte[] getBytes(short s, boolean bBigEnding) {
byte[] buf = new byte[2];
if (bBigEnding)
for (int i = buf.length - 1; i >= 0; i--) {
buf[i] = (byte) (s & 0x00ff);
s >>= 8;
}
else
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) (s & 0x00ff);
s >>= 8;
}
return buf;
}
public byte[] getBytes(int s, boolean bBigEnding) {
byte[] buf = new byte[4];
if (bBigEnding) {
for (int i = buf.length - 1; i >= 0; i--) {
buf[i] = (byte) (s & 0x000000ff);
s >>= 8;
}
} else {
System.out.println("1");
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) (s & 0x000000ff);
s >>= 8;
}
}
return buf;
}
public byte[] getBytes(long s, boolean bBigEnding) {
byte[] buf = new byte[8];
if (bBigEnding)
for (int i = buf.length - 1; i >= 0; i--) {
buf[i] = (byte) (s & 0x00000000000000ff);
s >>= 8;
}
else
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) (s & 0x00000000000000ff);
s >>= 8;
}
return buf;
}
public short getShort(byte[] buf, boolean bBigEnding) {
if (buf == null) {
throw new IllegalArgumentException("byte array is null!");
}
if (buf.length > 2) {
throw new IllegalArgumentException("byte array size > 2 !");
}
short r = 0;
if (bBigEnding) {
for (int i = 0; i < buf.length; i++) {
r