package mtmc.util object BinaryUtils { /** * @param start - a base 1 index to start at (16 is the most significant, 1 is the least) * @param totalBits - the total bits to get * @param value - the value to get the bits from */ fun getBits(start: Int, totalBits: Int, value: Short): Short { if (totalBits <= 0) { return 0 } val returnValue = (value.toInt() and 0xffff) ushr (start - totalBits) var mask = 0 var toShift = totalBits while (toShift > 0) { toShift-- mask = mask shl 1 mask = mask + 1 } return (returnValue and mask).toShort() } fun toBinary(aByte: Byte): String { val zeroed = aByte.toInt().toString(2).padStart(8, '0') val underScored = zeroed.replace("....".toRegex(), "$0_") val noTrailingUnderscore = underScored.substring(0, underScored.length - 1) return "0b" + noTrailingUnderscore } fun toBinary(aShort: Short): String { val zeroed = aShort.toInt().toString(2).padStart(16, '0') val underScored = zeroed.replace("....".toRegex(), "$0_") val noTrailingUnderscore = underScored.substring(0, underScored.length - 1) return "0b" + noTrailingUnderscore } fun toBinary(anInt: Int): String { val zeroed = anInt.toString(2).padStart(32, '0') val underScored = zeroed.replace("....".toRegex(), "$0_") val noTrailingUnderscore = underScored.substring(0, underScored.length - 1) return "0b" + noTrailingUnderscore } }