Mutual conversion of Int Byte in kotlin, commonly used

The transmission unit in serial communication is byte, and one byte occupies eight bits/8bit

Commonly used methods

1. Convert an Int to a byte and directly call the Int.toByte() method

See below for direct conversion

 var num = 23
 var num2Byte = num.toByte()
 println("mytest num $num num2Byte$num2Byte")

The results are all normal.
Insert image description here
What is the result if num=128 here?
Insert image description here

The result of converting to byte becomes -1. What is the specific reason? You can add some interesting knowledge about the original code's complement.
Therefore, if an int is to be converted into a byte without losing precision, the value range of the int must be between **[-128-127]**

2. Convert a byte to an int and directly call the Byte.toByte() method

 var byteNum = Byte.MAX_VALUE
 var byteNum2Int = byteNum.toInt()
 println("mytest byteNum $byteNum byteNum2Int$byteNum2Int")

Insert image description here

3. Convert an Int into a 4-byte byte array

   private fun intToByteArray4(num: Int): ByteArray {
    
    
        var byteArray = ByteArray(4)
        var highH = ((num shr 24) and 0xff).toByte()
        var highL = ((num shr 16) and 0xff).toByte()
        var LowH = ((num shr 8) and 0xff).toByte()
        var LowL = (num and 0xff).toByte()
        byteArray[0] = highH
        byteArray[1] = highL
        byteArray[2] = LowH
        byteArray[3] = LowL
        return byteArray
    }

Pass in 88
Insert image description here
and pass in Int.MAX_VALUE 2147483647.
Insert image description here
Why is [127,-1,-1,-1] here? Please think for yourself.

4. Convert an Int into a 2-byte byte array

 private fun intToByteArray2(num: Int): ByteArray {
    
    
        var byteArray = ByteArray(2)
        var LowH = ((num shr 8) and 0xff).toByte()
        var LowL = (num and 0xff).toByte()
        byteArray[0] = LowH
        byteArray[1] = LowL
        return byteArray
    }

4. Convert the byte array into an Int

ByteBuffer.wrap(bytes).int

Guess you like

Origin blog.csdn.net/qq910689331/article/details/107732001