'convert integer to binary number in numba

I'm using numba, and would like to convert an integer to a binary representation. In normal python I'd use bin() or np.binary_repr(). But these aren't supported in numba. Any advice? Should I just write a converter in numba from scratch?



Solution 1:[1]

If you are still interested this fn generate bin array via numba:

where size_of_bin is out length.


from numba import njit, prange
import numpy as np


@njit(fastmath=True)
def num_to_binary(number, size_of_bin = 32):
    out = np.zeros(size_of_bin)
    num = number
    index = 31

    for i in prange(size_of_bin):
        floatDivide = num // 2
        divide = num / 2
        if floatDivide != divide:
            out[index] = 1
    
        num = floatDivide
        
        index-= 1
        if index == -1 or floatDivide == 0:
            break

    return out

    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3300782