📄 bits.java
字号:
package org.trinet.util;
/**
* Staic classes for bit and byte manipulation.
*/
public class Bits {
/**
* Convert arbitrary number of bytes to integer converting the specified
* subarray of bytes using the platform's default character encoding.
*/
public static int byteStringToInt (byte[] buff, int start, int len)
{
String str = new String(buff, start, len);
Integer i = Integer.valueOf(new String(buff, start, len));
return ( i.intValue() ); // Integer -> int
}
/**
* Intepret 2 bytes as an integer. The bytes are taken from the byte array buff
* beginning at array index 'start' (first postion is 0).
* Uses the formula:
<tt>
(short)((a << 8) | (b & 0xff))
</tt)
* Note that "masking" (& 0xff) is necessary to preserve the original bit pattern
* because Java has no unsigned data types (except char)
*/
public static int byteToInt2 (byte[] buff, int start)
{
return (buff[start] << 8) | (buff[start+1] & 0xff);
}
/**
* Intepret 4 bytes as an integer. The bytes are taken from the byte array buff
* beginning at array index 'start' (first postion is 0).
*/
public static int byteToInt4 (byte[] buff, int i)
{
return ((buff[i] & 0xff) << 24) |
((buff[i+1] & 0xff) << 16) |
((buff[i+2] & 0xff) << 8) |
(buff[i+3] & 0xff);
}
/**
* Convert byte[] array containing 2-byte ints to int[] (4-bytes)
* How to convert 2 bytes to a signed short...
* (short)((a << 8) | (b & 0xff))
* Note that "masking" (& 0xff) is necessary to preserve the original bit pattern
* because Java has no unsigned data types (except char)
*/
public static int[] byteArrayToInt2 (byte[] b, int nbytes)
{
int[] in = new int[nbytes/2];
int idx=0;
short sht;
for (int i=0; i<nbytes; i=i+2)
{
in[idx] = (b[i] << 8) | (b[i+1] & 0xff);
idx++;
}
return (in);
}
/**
* Convert byte[] array containing 4-byte ints to int[] (4-bytes)
32-bit integer
If the bytes read, in order, are
b1, b2, b3, and b4, where 0 <= b1, b2, b3, b4 <= 255, then the
result is equal to:
(((a & 0xff) << 24) | ((b & 0xff) << 16) |
((c & 0xff) << 8) | (d & 0xff))
*/
public static int[] byteArrayToInt4 (byte[] b, int nbytes)
{
int[] in = new int[nbytes/4];
int idx=0;
for (int i=0; i<nbytes; i=i+4)
{
in[idx] = ((b[i] & 0xff) << 24) |
((b[i+1] & 0xff) << 16) |
((b[i+2] & 0xff) << 8) |
(b[i+3] & 0xff);
idx++;
}
return (in);
}
/**
* See if a bit is set.
* There must be a native Java way to do this but I can't find it.
* Bits are numbered starting at 0.
*/
public static boolean bitSet (byte b, int pos)
{
int val = (int) Math.pow(2, pos+1);
return (boolean) ((b & (byte) val)==val);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -