Last active
July 17, 2024 19:05
-
-
Save kepocnhh/b23cc6a5ef22261ae8c485ab00eaf900 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun toInt(b1: Byte, b2: Byte, b3: Byte, b4: Byte): Int { | |
return b1.toInt().and(0xff).shl(8 * 3) | |
.or(b2.toInt().and(0xff).shl(8 * 2)) | |
.or(b3.toInt().and(0xff).shl(8 * 1)) | |
.or(b4.toInt().and(0xff)) | |
} | |
// 0 1 2 3 | |
// 01234567 01234567 01234567 01234567 | |
// 01111111 10100001 10110010 11000011 | |
// 7f a1 b2 c3 | |
// 127 161 178 195 | |
fun bitsShifting() { | |
val int32: Int = 2141303491 | |
println("int32: $int32") | |
val b1: Byte = int32.shr(8 * 3).toByte() | |
val b2: Byte = int32.shr(8 * 2).toByte() | |
val b3: Byte = int32.shr(8 * 1).toByte() | |
val b4: Byte = int32.toByte() | |
println("b1: ${b1.toInt() and 0xff}($b1)") // 127(127) | |
println("b2: ${b2.toInt() and 0xff}($b2)") // 161(-95) | |
println("b3: ${b3.toInt() and 0xff}($b3)") // 178(-78) | |
println("b4: ${b4.toInt() and 0xff}($b4)") // 195(-61) | |
val decoded = toInt(b1, b2, b3, b4) | |
println("decoded: $decoded") | |
check(int32 == decoded) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment