Skip to content
/ bitty Public

bit manipulation library for Java and Kotlin

License

Notifications You must be signed in to change notification settings

elkin/bitty

Repository files navigation

bitty

Build Status Coverage

bit manipulation library for Java and Kotlin

Supported types

At the moment the library provides bit manipulation operations for the following Java types only: int, long, short. Also it provides extension functions for Kotlin types: Int, Long, Short. Kotlin supports operator overloading. It makes the code more concise. The library overrides indexed access operator for slice and bit operations on the supported types. Look at the usage examples below.

How it is organized

The library provides four utility classes for bit manipulation:

Each utility class provides bit manipulation operations for a corresponding type.

For each type(int, long, short) following bit manipulation operations are implemented:

  • get bits slice

  • set bits slice

  • clear bits slice

  • get bit by index

  • check if bit is set

  • set bit by index

  • clear bit by index

  • get byte

  • get number of non-zero bytes

  • clear higher order bytes

By default arguments aren’t validated. But for each operation there’s a corresponding version that validates arguments. Such operations have suffix "Safe". For example: methods IntegerUtil.getBitsSlice and IntegerUtil.getBitsSliceSafe.

Important
Lowest bit and byte indexes are zero.

Examples

  • Java

    // gets the first byte
    int intValue = BitUtil.getBitsSlice(0xFEFE, 0, 7);
    // value is equal to 0xFE
    
    long longValue = BitUtil.setBit(0x80L, 3);
    // longValue is equal to 0x88L
    
    byte byteValue = BitUtil.getByte((short)0x8880, 1);
    // byteValue is equal to 0x88
  • Kotlin

    235.getBitsSlice(2,4);
    
    // or the same using the get operator:
    235[2, 4]
    
    1024L.getBit(11)
    // using the get operator
    1024L[11]
    
    val shortValue = 128.toShort();
    shortValue.isBitSet(7);

Tests

All bit manipulation operations are tested. See coverage on the badge. You can find tests in the directory src/test/java/io/github/elkin/bitty.

Tests use nice library for property based testing: QuickTheories.