Kotlin bye数组与基本数据类型的转换(高位->低位、低位->高位)

//byte数组转成Int值  由高位到低位
fun byteArrayToInt(params:ByteArray): Int {
   var value = 0
   for (i in 0..3) {
      val shift = (4 - 1 - i) * 8
      value += params[i].toInt() and 0x000000FF shl shift 
   }
   return value
}
//byte数组转成Int值  由低位到高位
fun byteArrayToIntLH(data:ByteArray): Int{
   var count: Int = data[0].toInt() and 0xff
   count = count or (data[1].toInt() and 0xff shl 8)
   count = count or (data[2].toInt() and 0xff shl 16)
   count = count or (data[3].toInt() and 0xff shl 24)
   return count
}
//byte数组转short,高位在前,低位在后
fun byteArrayToShort(param:ByteArray): Short {
   var value = (param[0].toInt() and 0xFF) shl 8
   value = value or (param[1].toInt() and 0xff)
   return value.toShort()
}
//byte数组转short,低位在前,高位在后
fun byteToShortLittle(b: ByteArray): Short {
    return ((b[1].toInt() shl 8) or (b[0].toInt() and 0xff)).toShort()
 }
//byte数组转成Long值  由低位到高位
fun byteArrayToLongLH(param:ByteArray): Long{
    var result = 0L
    for (i in 0..7){
    	result += ((param[i].toLong() and 0xff) shl ((8-1-(7-i))*8))
    }
	return result
}
//byteArray转Long,高位在前,低位在后
fun byteArrayToLong(param:ByteArray): Long{
   var result = 0L
   for (i in 0..7){
      result += ((param[i].toLong() and 0xff) shl ((8-1-i)*8))
    }
    return result
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值