Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: decimal to binary

by Marshall (Canon)
on Jan 09, 2012 at 11:06 UTC ( [id://946985]=note: print w/replies, xml ) Need Help??


in reply to decimal to binary

I think the question has been answered, but I'll post a couple of other formulations for you. Sometimes seeing other programming techniques is helpful.

This is from a CRC program that was coded in assembly, C and Perl. The relevant part prints the 16 bit CRC values.

The Perl code:
A lab requirement was to print the 16 bits like: 0101 1011 1100 0001

printf "The CRC Bytes (binary) : %04b %04b %04b %04b\n", $CRC_byte1>>4, $CRC_byte1 & 0xF, $CRC_byte2>>4, $CRC_byte2 & 0xF;
In Perl, there is a %b "format spec" for printf - described on the sprintf man page. I didn't mess with a loop, and rather just used some simple binary shift and "and" operations to extract each group of 4 bits (a hex digit actually) from the 2 bytes comprising the 16 bit CRC value. In a case like this, with fixed format (always 16 binary digits), no loop is needed. Oh, I should point out that it is known that $CRC_byte1 and $CRC_byte2 only use 8 bits each.

The C code:
There is no %b format spec in standard C. So I did it a bit differently...

void dump_16bits(unsigned int any_16bits) { int i; for (i=0; i<16; i++) { if (i%4==0 )printf (" "); printf ("%c", (any_16bits & 0x8000) ? '1':'0'); any_16bits <<=1; #a keft shift 1 bit } }
This uses the modulo operator (%) to put a space in every 4 binary digits. The printf statement here prints '1' or '0' depending upon the most significant bit (specifically the 2**15 bit)

The modulo operator (%) and the ternary operator (any_16bits & 0x8000) ? '1':'0' both exist in Perl also and you may on occasion find a use for them. In this case, the Perl version if this was "translated as directly from C to Perl" as possible, would be almost identical.

This was a demo for my lab students and I used different techniques on purpose. I'll spare you the assembly code!

My purpose was just to demo some other techniques for you.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://946985]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-03-29 01:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found