Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arith
(number: int, shift_amount: int)
| 66 | |
| 67 | |
| 68 | def arithmetic_right_shift(number: int, shift_amount: int) -> str: |
| 69 | """ |
| 70 | Take in 2 integers. |
| 71 | 'number' is the integer to be arithmetically right shifted 'shift_amount' times. |
| 72 | i.e. (number >> shift_amount) |
| 73 | Return the shifted binary representation. |
| 74 | |
| 75 | >>> arithmetic_right_shift(0, 1) |
| 76 | '0b00' |
| 77 | >>> arithmetic_right_shift(1, 1) |
| 78 | '0b00' |
| 79 | >>> arithmetic_right_shift(-1, 1) |
| 80 | '0b11' |
| 81 | >>> arithmetic_right_shift(17, 2) |
| 82 | '0b000100' |
| 83 | >>> arithmetic_right_shift(-17, 2) |
| 84 | '0b111011' |
| 85 | >>> arithmetic_right_shift(-1983, 4) |
| 86 | '0b111110000100' |
| 87 | """ |
| 88 | if number >= 0: # Get binary representation of positive number |
| 89 | binary_number = "0" + str(bin(number)).strip("-")[2:] |
| 90 | else: # Get binary (2's complement) representation of negative number |
| 91 | binary_number_length = len(bin(number)[3:]) # Find 2's complement of number |
| 92 | binary_number = bin(abs(number) - (1 << binary_number_length))[3:] |
| 93 | binary_number = ( |
| 94 | "1" + "0" * (binary_number_length - len(binary_number)) + binary_number |
| 95 | ) |
| 96 | |
| 97 | if shift_amount >= len(binary_number): |
| 98 | return "0b" + binary_number[0] * len(binary_number) |
| 99 | return ( |
| 100 | "0b" |
| 101 | + binary_number[0] * shift_amount |
| 102 | + binary_number[: len(binary_number) - shift_amount] |
| 103 | ) |
| 104 | |
| 105 | |
| 106 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected