Android Kotlin 对字节 byte 中的某一位 bit 取反

更新日期: 2023-09-27 阅读次数: 626 字数: 216 分类: Android

Android Kotlin 中,需要对字节 byte 中的某一位 bit 取反

取反代码

fun toggleBit(byteValue: Byte, bitIndex: Int): Byte {
    // Convert the Byte to an Int to perform bitwise operations
    val intValue = byteValue.toInt()

    // Create a mask with the bit at the specified index set to 1
    val mask = 1 shl bitIndex

    // Use bitwise XOR operation to toggle the bit
    val result = intValue xor mask

    // Convert the result back to a Byte
    return result.toByte()
}

单元测试

class ExampleUnitTest {
    @Test
    fun toggleBitInByte() {
        val byteValue: Byte = 0b00001100 // 初始字节值
        val bitIndex = 3 // 要取反的位的索引(0-7)

        val newByteValue = toggleBit(byteValue, bitIndex)
        val result = newByteValue.toString(2)
        println("toggleBitInByte result: $result") // 输出:100,索引为 3 的位被取反
        assertEquals("100", result)
    }

    @Test
    fun toggleBitInByte2() {
        val byteValue: Byte = 0b00000100 // 初始字节值
        val bitIndex = 3 // 要取反的位的索引(0-7)

        val newByteValue = toggleBit(byteValue, bitIndex)
        val result = newByteValue.toString(2)
        println("toggleBitInByte2 result: $result") // 输出:100,索引为 3 的位被取反
        assertEquals("1100", result)
    }
}

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式