I am trying to find the fastest possible way to convert a binary string to an array of integer 0
and 1
. I am currently using python 3.8, and have the following two functions to obtain such array:
import numpy as np
from typing import Literal, Sequence
def string_to_array(Bin_String):
Bin_array=[int(Bin_String[i],2) for i in range(len(Bin_String))]
return Bin_array
def string_to_array_LtSq(string: Sequence[Literal['0', '1']]) -> np.ndarray:
return np.array([int(c) for c in string])
For a string of length 1024, string_to_array_LtSq
function takes 20 micro-seconds less than the other (average 370 micro-seconds) though I don't understand why it is faster since both are using int
function.
But this is an important part of the code, so is there a faster way in python?
Also, is it possible to do faster in any other language (for example c)? I might switch to that language.
Thanks.
Related Post: