develooper Front page | perl.fwp | Postings from April 2003

Increment binary string

Thread Next
From:
Quantum Mechanic
Date:
April 24, 2003 14:03
Subject:
Increment binary string
Message ID:
20030424210300.82162.qmail@web14007.mail.yahoo.com
Recently, someone asked me how to increment an
arbitrary string representing an unsigned binary
integer. Among the more obvious answers using pack,
unpack, and/or oct, was this:

   s/(0?)(1*)$/1 . (0 x length($2))/e;

Which produces results such as:

  0 => 1
  1 => 10
  01 => 10
  11 => 100
  100 => 101
  111000111 => 111001000
  0101010101 => 0101010110
  0000011111 => 0000100000

I tried googling, but didn't find anything that seemed
similar, so I'll ask the list...

Is there something better (read: more interesting) for
this?

What about decrementing?


=====
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Quantum Mechanics: The dreams stuff is made of

__________________________________________________
Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo
http://search.yahoo.com

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About