diff --git a/src/main/kotlin/BinConvert.kt b/src/main/kotlin/BinConvert.kt index 19d05a2..d3d45d0 100644 --- a/src/main/kotlin/BinConvert.kt +++ b/src/main/kotlin/BinConvert.kt @@ -96,25 +96,32 @@ object BinConvert { /** * */ - fun Short.insertBit(register: Int, value: Int): Long { - if (register < 0) throw IllegalArgumentException("Регистр не может быть отрицальтельным") - if (value !in 0..1) throw IllegalArgumentException("Значение не должно быть больше 1 и меньше 0") + fun Short.insertBit(register: Int, value: Int): Short { + if (register < 0 || register > 15) + throw IllegalArgumentException("Регистр должен быть в диапазоне 0-15") + if (value !in 0..1) + throw IllegalArgumentException("Значение должно быть 0 или 1") - var binString = this.toBinaryActual() + var binString = this.toBinaryPadded() val chars = binString.toCharArray() // Рассчитываем индекс в массиве с учетом отсчета справа налево val stringIndex = chars.lastIndex - register - // Безопасно вставляем текстовый символ '1' или '0' + // Вставляем значение в нужный регистр chars[stringIndex] = if (value == 1) '1' else '0' binString = String(chars) // Парсим бинарную строку обратно в число - return binString.toLong(2) + return binString.toShort(2) } + fun Short.toBinaryPadded(): String { + // Преобразуем в двоичную строку без знака и дополняем нулями до 16 бит + val unsignedInt = this.toInt() and 0xFFFF + return unsignedInt.toString(2).padStart(16, '0') + } fun Short.toBinaryActual(): String = this.toString(2) } \ No newline at end of file diff --git a/src/test/kotlin/InsertBinTest.kt b/src/test/kotlin/InsertBinTest.kt index 5c15bdd..e9e8372 100644 --- a/src/test/kotlin/InsertBinTest.kt +++ b/src/test/kotlin/InsertBinTest.kt @@ -1,5 +1,5 @@ import ru.thiflict.binaryutils.BinConvert.insertBit fun main() { - println(48.toShort().insertBit(0, 1)) + println(4.toShort().insertBit(6, 1)) } \ No newline at end of file