Derek Halden
Derek Halden

Reputation: 2333

Fixed length, 6-bit binary string in perl

Is it possible to print a fixed length binary string in perl of binary characters? What I have so far, is this:

printf(OUTFILE "%b\n", $nextToken);

But this only prints out relevant bits. i.e. If $nextToken = 3, then the string only prints out:

11

What I want it to print out, is:

000011

Is there an easy way to get perl to print out the extra 4 characters to make this a 6-character long binary string?

Upvotes: 2

Views: 676

Answers (2)

Miller
Miller

Reputation: 35208

Check out the docs for sprintf. The very first example shows how to add leading 0's

printf(OUTFILE "%06b\n", $nextToken);

Upvotes: 3

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137467

I think "%06b" is what you want.

Looking at the sprintf docs, you can see that the 0 means "use zeros, not spaces, to right-justify", and the 6 is the minimum width to be printed.

Upvotes: 1

Related Questions