android 大小端转换器,android网络传输中的大小端转换

public static byte[] little_intToByte(int i, int len) {

byte[] abyte = new byte[len];

if (len == 1) {

abyte[0] = (byte) (0xff & i);

} else if (len == 2) {

abyte[0] = (byte) (0xff & i);

abyte[1] = (byte) ((0xff00 & i) >> 8);

} else {

abyte[0] = (byte) (0xff & i);

abyte[1] = (byte) ((0xff00 & i) >> 8);

abyte[2] = (byte) ((0xff0000 & i) >> 16);

abyte[3] = (byte) ((0xff000000 & i) >> 24);

}

return abyte;

}

public static int little_bytesToInt(byte[] bytes) {

int addr = 0;

if (bytes.length == 1) {

addr = bytes[0] & 0xFF;

} else if (bytes.length == 2) {

addr = bytes[0] & 0xFF;

addr |= (((int) bytes[1] << 8) & 0xFF00);

} else {

addr = bytes[0] & 0xFF;

addr |= (((int) bytes[1] << 8) & 0xFF00);

addr |= (((int) bytes[2] << 16) & 0xFF0000);

addr |= (((int) bytes[3] << 24) & 0xFF000000);

}

return addr;

}

/**

* int to byte[] 支持 1或者 4 个字节

*

* @param i

* @param len

* @return

*/

public static byte[] big_intToByte(int i, int len) {

byte[] abyte = new byte[len];

;

if (len == 1) {

abyte[0] = (byte) (0xff & i);

} else if (len == 2) {

abyte[0] = (byte) ((i >>> 8) & 0xff);

abyte[1] = (byte) (i & 0xff);

} else {

abyte[0] = (byte) ((i >>> 24) & 0xff);

abyte[1] = (byte) ((i >>> 16) & 0xff);

abyte[2] = (byte) ((i >>> 8) & 0xff);

abyte[3] = (byte) (i & 0xff);

}

return abyte;

}

public static int big_bytesToInt(byte[] bytes) {

int addr = 0;

if (bytes.length == 1) {

addr = bytes[0] & 0xFF;

} else if (bytes.length == 2) {

addr = bytes[0] & 0xFF;

addr = (addr << 8) | (bytes[1] & 0xff);

} else {

addr = bytes[0] & 0xFF;

addr = (addr << 8) | (bytes[1] & 0xff);

addr = (addr << 8) | (bytes[2] & 0xff);

addr = (addr << 8) | (bytes[3] & 0xff);

}

return addr;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值