0

I am slicing 24 digits long binary number into three 8digits long numbers. Here is my code below:

def extract_number(number):
    number_in_string = str(number)
    red = number_in_string[:8]
    green = number_in_string[8:16]
    blue = number_in_string[16:24]
    return [int(red), int(green), int(blue)]

if __name__ == '__main__':
    print(extract_number(101111010110011011100100))

The result i get from the terminal is

[10111101, 1100110, 11100100]

The problem occurs in the 2nd number. It's digit is not 8 digits long when I did number_in_string[8:16]. And I using slice function wrong here?

2 Answers 2

2

You use slice function correctly

In [28]: str(101111010110011011100100)[8:16]
Out[28]: '01100110'

The second number has leading zero which is omitted once you convert string to integer.

In [29]: int('01100110')
Out[29]: 1100110

You use numbers represented in decimal base, but mention binary base. Is there a reason for this? I would like to recommend you to use binary base

def extract_number(number):
    number_in_string = bin(number)[2:]
    red = number_in_string[:8]
    green = number_in_string[8:16]
    blue = number_in_string[16:24]
    return [int(red, 2), int(green, 2), int(blue, 2)]

if __name__ == '__main__':
    print(extract_number(0b101111010110011011100100))

The code above outputs

[189, 102, 228]

If you need binary representations of these numbers use builtin bin function

Sign up to request clarification or add additional context in comments.

Comments

1

Try returning the strings as they are. Converting them to integers will remove any leading zeroes from the string, if present. Corrected code here-

def extract_number(number):
    number_in_string = str(number)
    red = number_in_string[:8]
    green = number_in_string[8:16]
    blue = number_in_string[16:24]
    return [red, green, blue]

if __name__ == '__main__':
    print(extract_number(101111010110011011100100))

Output-

['10111101', '01100110', '11100100']

3 Comments

Hey! I do not see any changes here 0_0
@Kahsn I don't see why you don't see any changes. Check the answer again. I have updated it with the output. Note, I am returning the sliced strings without casting them to integers.
Oh my bad. I totally missed the int() part. Gottcha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.