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)
    }
}