So, I am learning Python. To help my understanding, I was wondering how someone might make this code more efficient.

Purpose:
Take a 32-bit value (tempCode) and output each nibble. My way was to use a string, basically shifting out the binary value from bit 0 to bit 31 into the string.

i = 1
        binString = ''
        regSize = 32

        while (i <= regSize):
            binString = str(tempCode & 1) + binString
            tempCode >>= 1
            if ( (i%4) == 0 ): binString = ' ' + binString
            i += 1
            
        print "In binary: ", binString, "\n"

Output would be:
You entered: 0xF0A
In binary: 0000 0000 0000 0000 0000 1111 0000 1010

Your code is quite well, anyway two more ways to do it: masking with 0b1111 and using the bin representation string:

## 1) do it yourself with masking
def nibble(n,x):
    ## mask 0b1111 shift up, mask, shift back
    return ( x & ( 0b1111 << (4 * n) ) ) >> (4 * n)

x=0xF0a
regSize = 32

for i in reversed(range(8)):
    ## bin, take out 0b, zerofill and print
    print (bin(nibble(i,x))[2:]).zfill(4),
print

##  2) other way if you do not want to do yourself
bx=bin(x)[2:].zfill(regSize)

for i in range(0,len(bx),4):
    print bx[i:i+4],

Awesome. Thank you for the reply, it helps is seeing other methods to do the same thing. Though I do prefer the 32-bit output to remain on a single line. Is there a way when using PRINT in a loop, to not automatically include a carriage return?

print does not automatically include carriage return, but does add space between inputs. It adds carriage return only if you do not finish print with comma(,).

Output of my code is

>>> 
0000 0000 0000 0000 0000 1111 0000 1010
0000 0000 0000 0000 0000 1111 0000 1010
>>>

If you want not to have space between printed things you can concatenate them in string and print the string, you can do from __future__ import print_function and use end='' parameter, or you can import sys and do sys.stdout.write() instead of printing.

Edited 6 Years Ago by pyTony: n/a

See, look at my C-coding skills causing errors. I thought that comma was a typo ;)

Thanks. I like the condensed code in option 2 above.

This question has already been answered. Start a new discussion instead.