比如:
byte[] bs=new byte[6];要前面4字节填充一个int,后面两个字节填一个short.
byte[] bs=new byte[6];要前面4字节填充一个int,后面两个字节填一个short.
解决方案 »
- js题求答案
- 怎么在myeclipse8.5中使用debug功能,具体怎么做,请大神们说清楚点,谢谢了
- 怎么import import static net.mindview.util.SwingConsole.*;这个包?
- J2SE新手提问超多,请大家帮忙。谢谢了。
- “包”使用的小麻烦
- java post的问题(手机炸弹)
- 无法 import javax.jdo.*; ??我已经装了jdk5
- 谁能帮我找找错误~~!一个javaBean程序~~高手请进~~~~!!
- 异常~——基类方法未throws自类可以throws么??~~
- java 如何使成员方法不改变数据成员
- 这个说法对吗??
- 很弱智的问题
import java.util.Arrays;public class Test { public static void main(String[] args) {
byte[] bs = new byte[] { 1, 2, 3, 4, 5, 6 };
System.out.println(bytes2int(bs, 0));
System.out.println(bytes2short(bs, 4));
System.out.println(Arrays.toString(int2bytes(16909060)));
System.out.println(Arrays.toString(short2bytes((short) 1286))); } static int bytes2int(byte[] b, int startIndex) {
int re = 0;
for (int i = startIndex; i < startIndex + 4; i++) {
re <<= 8;
re += b[i];
}
return re;
} static short bytes2short(byte[] b, int startIndex) {
short re = 0;
for (int i = startIndex; i < startIndex + 2; i++) {
re <<= 8;
re += b[i];
}
return re;
} static byte[] int2bytes(int x) {
byte[] b = new byte[4];
for (int i = b.length; i > 0; i--) {
b[i - 1] = (byte) x;
x >>= 8;
}
return b;
} static byte[] short2bytes(short x) {
byte[] b = new byte[2];
for (int i = b.length; i > 0; i--) {
b[i - 1] = (byte) x;
x >>= 8;
}
return b;
}}
staID=byteHead[6];
pdaID=byteHead[7];
contLen=System.BitConverter.ToInt16(byteHead,8);
ascSum=System.BitConverter.ToInt16(byteHead,10);
int i=10;
int j=30;
memcpy(bs,&i,4);
memcpy(&bs[4],&j,4);
> memcpy(bs,&i,4);这种简单是有代价的,它要求“网络传输的数据流”跟“本机的数据内部表示法”是一致的,比如,对于一个“整数”,就存在“数据宽度”和“字节顺序”的问题。Java 中没有这么“简单”的操作,就是为了避免这种“危险的代价”。你自己根据“协议”要求实现一套转换算法,就像 dreamover(梦醒了) 那样,既安全可靠,又简单方便(毕竟一劳永逸的事情嘛)