Peter’s blog ✴ Week 120 ✴ 5 July 2021

THE WEEKLY CHALLENGE
Bits and angles

The Perl Camel

Task 1

Swap odd/even bits

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.

Examples


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.

Analysis

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.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 123

Script


#!/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];
}

11 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


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