问个byte数组的问题

_梦 2010-05-06 05:27:19
有个int i=12345678;
怎么放入4长度的byte[] b=new byte[4]中,坐等强人!
...全文
125 9 打赏 收藏 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
notlogin 2010-05-06
  • 打赏
  • 举报
回复
不会 再看看其他答案
abc130314 2010-05-06
  • 打赏
  • 举报
回复
b[0]=(byte)(0xff & (i >> 24))
b[1]=(byte)(0xff & (i >> 16))
b[2]=(byte)(0xff & (i >> 8))
b[3]=(byte)(0xff & i)
_梦 2010-05-06
  • 打赏
  • 举报
回复
6楼的还可以接受
keeya0416 2010-05-06
  • 打赏
  • 举报
回复
写个蛋疼的硬编码

public class Test {
public static void main(String[] args) {
int i=12345678;
byte[] b=new byte[4];
for(int m = 0; m < b.length; m++){
b[m] =(byte)( i % 100);
i /= 100;
}
}
}

_梦 2010-05-06
  • 打赏
  • 举报
回复
我晕,这么多
  • 打赏
  • 举报
回复
public class ScoreTest {

public static void main(String[] args) {
byte[] be = int2BytesBE(0xcc123abc);
System.out.println(ByteUtil.bytes2StrSpace(be));

byte[] le = int2BytesLE(0xcc123abc);
System.out.println(ByteUtil.bytes2StrSpace(le));
}

public static byte[] int2BytesBE(int num) {
return int2Bytes(num, true);
}

public static byte[] int2BytesLE(int num) {
return int2Bytes(num, false);
}

public static byte[] int2Bytes(int num, boolean isBigEndian) {
final int len = Integer.SIZE / Byte.SIZE;
byte[] bys = new byte[len];
for(int i = 0; i < len; i++) {
int shift = isBigEndian ? (len - 1 - i) * Byte.SIZE : (i * Byte.SIZE);
bys[i] = (byte)((num >>> shift) & 0xff);
}
return bys;
}
}

class ByteUtil {

private final static char[] HEX = "0123456789abcdef".toCharArray();

private ByteUtil() { }

public static String bytes2StrSpace(byte[] bys) {
char[] chs = new char[bys.length * 3 - 1];
for(int i = 0, k = 0; i < bys.length; i++) {
if(k > 0) {
chs[k++] = ' ';
}
chs[k++] = HEX[(bys[i] >> 4) & 0xf];
chs[k++] = HEX[bys[i] & 0xf];
}
return new String(chs);
}
}
fephy 2010-05-06
  • 打赏
  • 举报
回复
都搞java
c++没人理财了么?
_梦 2010-05-06
  • 打赏
  • 举报
回复
啊....默认是啥就是啥
  • 打赏
  • 举报
回复
字节序采用 Big-Endian 还是 Little-Endian?

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧