Peter’s blog ✴ Week 119 ✴ 28 June 2021

THE WEEKLY CHALLENGE
Swap and sequence

The Perl Camel

Task 1

Swap nibbles

You are given a positive integer $N. Write a script to swap the two nibbles of the binary representation of the given number and print the decimal number of the new binary representation. A nibble is a four-bit aggregation, or half an octet. To keep the task simple, we only allow integers less than or equal to 255.

Examples


Input: $N = 101
Output: 86

Binary representation of decimal 101 is 1100101 or as 2 
nibbles (0110)(0101). The swapped nibbles would be 
(0101)(0110) same as decimal 86.

Input: $N = 18
Output: 33

Binary representation of decimal 18 is 10010 or as 2 
nibbles (0001)(0010). The swapped nibbles would be 
(0010)(0001) same as decimal 33.

Analysis

To do this we first convert $N to its binary representation using sprintf('%08b', $N). The nibbles are then easily switched, and the new binary number is converted to decimal by multiplying the 1 bits by the appropriate power of 2 and adding those together.

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-06-28
use utf8;     # Week 119 - task 1 - Swap nibbles
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

swap_nibbles(101);
swap_nibbles(18);
swap_nibbles(243);

sub swap_nibbles {
    
    my ($input, $text, $flipped, $output, $n, $k);
    
    # initialise
    $input = $_[0];
    
    $text = sprintf('%08b', $input);
    $text =~ m|(..)(..)(..)(..)|;
    $flipped = $3 . $4 . $1 . $2;
    $n = 128;
    for $k (split('', $flipped)) {
        $output += $n * $k;
        $n /= 2;
    }
    
    say qq[\nInput:  $input = $1 $2 $3 $4];
    say qq[Output: $output = $3 $4 $1 $2];
}

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

Output from script


Input:  101 = 01 10 01 01
Output: 86 = 01 01 01 10

Input:  18 = 00 01 00 10
Output: 33 = 00 10 00 01

Input:  243 = 11 11 00 11
Output: 63 = 00 11 11 11

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain