0

I have the following predefined codes that represent an index in a binary bitmap:

0 = standard
1 = special
2 = regular
3 = late
4 = early
5 = on time
6 = generic 
7 = rfu

An example value I would take as an input would be 213, which becomes 11010101 in binary. Index 0, 2, 4, 6, and 7 have their bit flipped indicating that this record is: standard + regular + early + generic + rfu.

I am trying to figure out in perl how to take that binary data and build a string, like mentioned above with code + code + code, etc.

Any help would be greatly appreciated. Thanks.

Edit: My thoughts on how I might approach this are:

  1. Convert decimal to binary
  2. Find length of binary string
  3. Using substr get the value (0 or 1) index by index
  4. If index value = 1 then add relevant code to string

Is there a better way to go about this?

1
  • Have you tried anything? Is the problem that you don't know how to code this in Perl, or that you don't know of an algorithm to do this? Oct 2, 2013 at 21:47

1 Answer 1

4

You can test bits on input from 0 to 7, and take only these that are set,

my $in = 213;
my @r = ("standard","special","regular","late","early","on time","generic","rfu");

print join " + ", @r[ grep { $in & (1 << $_) } 0 .. $#r ];

# or
# print join " + ", map { $in & (1<<$_) ? $r[$_] : () } 0 .. $#r;

output

standard + regular + early + generic + rfu
2
  • 1
    Depending on how you think, 1 << $_ might be clearer than 2**$_. Instead of map { x ? y : () }, a grep+slice might be better: @r[ grep { $in & 1 << $_ } 0 .. $#r ].
    – amon
    Oct 2, 2013 at 22:03
  • @amon btw, it seems that ** is slower as it uses C pow function
    – mpapec
    Oct 2, 2013 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.