// Binary.kt Copyright (c) Kari Laitinen // http://www.naturalprogramming.com // 2020-10-31 File created. /* Kotlin documentation says that bitwise operators work only with types int and long. */ fun print_in_binary_form( given_integer : Int ) { var bit_mask : Int = -2147483648 // equals to 0x80000000 (Long literal) for ( bit_counter in 1 .. 32 ) { val one_bit_in_given_integer = given_integer and bit_mask if ( one_bit_in_given_integer == 0 ) { print( "0" ) } else { print( "1" ) } bit_mask = bit_mask ushr 1 // unsigned shift right } } fun main() { var test_number = 0x9A9A print( "\n Original test number: " ) print_in_binary_form( test_number ) print( "\n Twice left-shifted form: " ) test_number = test_number shl 2 print_in_binary_form( test_number ) print( "\n Back to original form: " ) test_number = test_number shr 2 print_in_binary_form( test_number ) print( "\n Last four bits zeroed: " ) test_number = test_number and 0xFFF0 print_in_binary_form( test_number ) print( "\n Last four bits to one: " ) test_number = test_number or 0x000F print_in_binary_form( test_number ) print( "\n A complemented form: " ) test_number = test_number.inv() print_in_binary_form( test_number ) print( "\n Exclusive OR with 0xF0F0: " ) test_number = test_number xor 0xF0F0 print_in_binary_form( test_number ) print( "\n Double right shift with shr: " ) test_number = test_number shr 2 print_in_binary_form( test_number ) print( "\n Double right shift with ushr: " ) test_number = test_number ushr 2 print_in_binary_form( test_number ) print( "\n\n" ) }