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
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.printf "The CRC Bytes (binary) : %04b %04b %04b %04b\n", $CRC_byte1>>4, $CRC_byte1 & 0xF, $CRC_byte2>>4, $CRC_byte2 & 0xF;
The C code:
There is no %b format spec in standard C. So I did it a bit differently...
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)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 } }
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 reply to Re: decimal to binary
by Marshall
in thread decimal to binary
by divyaimca
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |