Bits and angles
Weekly challenge 120 — 5 July 2021
Week 120: 5 Jul 2021
You are given a positive integer $N less than or equal to 255.
Write a script to swap the odd positioned bit with even positioned bit and print the decimal equivalent of the new binary representation.
Input: $N = 101 Output: 154 Binary representation of the given number is 01 10 01 01. The new binary representation after the odd/even swap is 10 01 10 10. The decimal equivalent of 10011010 is 154. Input: $N = 18 Output: 33 Binary representation of the given number is 00 01 00 10. The new binary representation after the odd/even swap is 00 10 00 01. The decimal equivalent of 100001 is 33.
The answer is given either ~ $N or equivalently 255 - $N.
Displaying the input and output numbers as paired binary
numbers can be done with:
$text = sprintf('%08b', $N);
$text =~ s|(\d\d)|$1 |g;
And that's it.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2021-07-05 use utf8; # Week 120 - task 1 - Swop odd/even bits use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; swap_odd_even_bits (101); swap_odd_even_bits (255); swap_odd_even_bits (0); swap_odd_even_bits (0b10101010); sub swap_odd_even_bits { my ($input, $bits, $text, $output); # initialise $input = shift; $bits = $input & 255; $text = sprintf('%08b', $bits); $text =~ s|(\d\d)|$1 |g; say qq[\nInput: $input = $text]; $bits = ~$bits & 255; $text = sprintf('%08b', $bits); $text =~ s|(\d\d)|$1 |g; say qq[Output: $bits = $text]; }
last updated 2026-03-13 — 11 lines of code
Input: 101 = 01 10 01 01 Output: 154 = 10 01 10 10 Input: 255 = 11 11 11 11 Output: 0 = 00 00 00 00 Input: 0 = 00 00 00 00 Output: 255 = 11 11 11 11 Input: 170 = 10 10 10 10 Output: 85 = 01 01 01 01
Any content of this website which has been created by Peter Campbell Smith is in the public domain