Your skill will accomplish what the force of many cannot |
|
PerlMonks |
Re: decimal to binaryby Marshall (Canon) |
on Jan 09, 2012 at 11:06 UTC ( [id://946985]=note: print w/replies, xml ) | Need Help?? |
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: 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: 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.
In Section
Seekers of Perl Wisdom
|
|