Search code examples
perlbitwise-operatorssubroutine

Extracting a set of values from a single integer


I have a number of things (let's call them nodes... it doesn't matter), conveniently referred to as node1, node2, ... nodeN.

The tricky part is that i need have a perl subroutine that takes an integer that refers to a set of nodes. My approach is this:

  1. Each node is given a value based on powers of 2, like this:

    • node1 = 1
    • node2 = 2
    • node3 = 4
    • node4 = 8
    • ...
    • node8 = 128
    • etc
  2. The value for each node is added up to produce an integer. For example, nodes 1, 3, 4 and 7 results in as integer of 77.

Now, how would I go about creating a subroutine that takes an integer like that and returns an array of node numbers?


PS:

  • The maximum amount of nodes is configurable. 16 is a reasonable max.
  • If I am approaching this an overly cumbersome way, I'm open to suggestions for a better way of producing a set of nodes from a single value.

Solution

  • Set $max to the number of nodes (e.g. 16).

    sub nodes {
        my $num = shift;
        return grep { $num & 2 ** $_ } 1 .. $max - 1;
    }