perl oct(‘0b…’) to interpret binary strings

This is really a quick reminder about a perl function which does a little more than you’d perhaps expect. Need to convert a binary (or hex or octal) string to an integer? The perl documentation for the oct(EXPR) function starts out with:

Interprets EXPR as an octal string and returns the corresponding value.

Then includes the comment:

(If EXPR happens to start off with 0x, interprets it as a hex string. If EXPR starts off with 0b, it is interpreted as a binary string. Leading whitespace is ignored in all three cases.)

So that’s handy:

DB<1> p oct(‘0555’) # octal
365
DB<2> p oct(‘0b101101101’) # binary
365
DB<3> p oct(‘0x16d’) # hex
365

Reversing what we can do in printf/sprintf :

DB<4> printf(“%04o\n%b\n%x\n”, 365, 365, 365)
0555
101101101
16d

Leave a Reply

Your email address will not be published. Required fields are marked *