Ask coding questions

← Back to all posts
How do I code a program to perform a logical shift to the left with binary numbers?
arthurabelo (0)

I would like a program that added a zero to the first position in the right, resulting in a shift to the left of the binary number.

JoshDaBosh (77)

if you're talking about LSHIFT, this would be it in Python:

def lshift(x, am):
        if am >= 8:
                 return "00000000"
        return (x[am:]).ljust(8, "0")

There may be better ways to do it, but that was the quickest way I could think of.

pyelias (1229)

Most languages have an operator to do this, <<. In this case you could use it like number << 1. If you are using a language that doesn't have this, multiplying by 2 will have the same effect.