2

I want to convert four character string text into 32bit integer number, e.g. four space string should return 0x20202020. All string elements are ASCII. I know that something like this works

number = ord(text[0]) << 24 | ord(text[1]) << 16 | ord(text[2]) << 8 | ord(text[3]) << 0

but it is rather slow and inefficient. Is there any faster way?

EDIT: This is meant to part of the algorithm sending a string to LCD display via C/Assembler script. String has to be split into list containing numbers that represent four characters each.

Regards.

3
  • maybe id(text) might be an option, depending on your application Commented Dec 8, 2019 at 11:34
  • 3
    What purpose does this conversion serve? Commented Dec 8, 2019 at 11:35
  • @schwobaseggl To send data to C/Assembler script which then sends it to LCD display Commented Dec 8, 2019 at 11:46

1 Answer 1

4

You could use text => bytes => int:

int.from_bytes(text.encode(),'big')

A quick time comparison:

import timeit

print(timeit.timeit("int.from_bytes(text.encode(),'big')","text = 'abcd'"))
print(timeit.timeit("ord(text[0]) << 24 | ord(text[1]) << 16 | ord(text[2]) << 8 | ord(text[3]) << 0","text = 'abcd'"))

Output:

0.21847990699999997
0.4186516309999999

So it seems that int.from_bytes is roughly twice as fast as the explicit bit shifting.

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

Comments

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.