Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The inv() function in Kotlin performs a bitwise inversion (also known as a bitwise NOT operation) on integer data types. It systematically flips every bit in the binary representation of the operand, converting all 0 bits to 1 and all 1 bits to 0. Unlike languages such as Java or C++ that utilize the tilde (~) symbol for bitwise NOT operations, Kotlin implements bitwise operations as named functions. For signed integers, the inv() function is exclusively available on Int and Long. Because Kotlin represents signed integers using two’s complement, applying the inv() function to a value x mathematically equates to -(x + 1). The sign bit is flipped along with the magnitude bits, which inherently changes the sign of the integer.
val a: Int = 43
// Binary representation (32-bit): 
// 00000000 00000000 00000000 00101011

val b: Int = a.inv()
// Binary representation after inv() (32-bit): 
// 11111111 11111111 11111111 11010100
// Decimal equivalent: -44

val c: Long = 1L
val d: Long = c.inv()
// Binary representation after inv() (64-bit):
// 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111110
// Decimal equivalent: -2

Handling Smaller Signed Types

The inv() function is not a member of the signed Byte or Short classes. To perform a bitwise inversion on these smaller integral types, the value must be explicitly widened to an Int, inverted, and then narrowed back to the original type.
val byteValue: Byte = 0b00001111 // Decimal: 15

// val errorByte = byteValue.inv() // COMPILATION ERROR: Unresolved reference: inv

val invertedByte: Byte = byteValue.toInt().inv().toByte() 
// Binary: 11110000
// Decimal equivalent: -16

Unsigned Types

Kotlin also supports inv() on all unsigned integer types (UByte, UShort, UInt, ULong). Unlike their signed counterparts, smaller unsigned types like UByte and UShort possess their own bitwise member functions and preserve their data types without requiring manual widening. The bit-flipping mechanism remains identical, but because unsigned types do not use a sign bit or two’s complement for negative values, the resulting decimal interpretation differs significantly from signed types.
val uByteVal: UByte = 15u
val invertedUByte: UByte = uByteVal.inv() // Compiles directly, type is preserved
// Binary: 11110000
// Decimal equivalent: 240

val uIntVal: UInt = 43u
// Binary: 00000000 00000000 00000000 00101011

val invertedUInt: UInt = uIntVal.inv()
// Binary: 11111111 11111111 11111111 11010100
// Decimal equivalent: 4294967252
Master Kotlin with Deep Grasping Methodology!Learn More