Home > Blockchain >  How to generate x no of 1s in python
How to generate x no of 1s in python

Time:06-17

So, the thing is I want to convert IP prefix into subnet mask. For that I need to generate x no of 1s and 0s. For eg: If the prefix is 21 I should generate :

11111111.11111111.11111000.00000000

so how can I do that ? Thank you.

CodePudding user response:

Solution I mentioned in my comment:

  1. make a string of x ones
  2. fill up to 32 chars with zeros
  3. slice it into 4 parts of length 8 and put dots between them
def subnet_mask_binary(x):
    ones = '1' * x
    mask = ones.ljust(32, '0')
    return f'{mask[:8]}.{mask[8:16]}.{mask[16:24]}.{mask[24:]}' 

CodePudding user response:

Here is my solution.

x = 21  # number of 1 in ip
rlist = []

for _ in range (x//8): #finding the octaves which only contains 1
    part = '11111111'
    rlist.append(part) 

r = ''
for _ in range(x%8): #counting number of 1 in mixed octaves [eg:11110000 count(1) = 4]
    r  = '1'


for _ in range((32-x)%8): #counting number of 0 in mix octaves [eg:11110000 count(0) = 4]
    r = '0'

rlist.append(r)
for _ in range((32-x)//8): #finding the octaves which only contains 0
    rlist.append('00000000')


final_ip = '.'.join(rlist) #joining all the parts in the list with '.' as separator

print(final_ip)

This is a very lengthy and less efficient way, but it does the task.

CodePudding user response:

Here's my solution to this problem.

def prefixToMask( n ):
    mask = ""

    lenghts = [ 8, 17, 26 ]

    for i in range(n):
        mask = mask   '1'
        if len(mask) in lenghts:
            mask = mask   '.'
        
        
    for i in range(32-n):
        if len(mask) in lenghts:
            mask = mask   '.'
        mask = mask   '0'

    return mask

For example

prefixToMask(21)

will return

11111111.11111111.11111000.00000000
  • Related