Wednesday, August 10, 2022

[FIXED] How can I convert decimal to binary values in python?

Issue

I'm novice in python and I developed a function which retrieve decimal values when the code function is equal to 1 and converts them to the binary values but the problem is that it returns a empty list while the list contains a values. I have to get a full list

Here is the function:

def coil_val_list(s):
    v = []
    r = []
    i = []
    for p in s:
        if p.haslayer('ModbusADUResponse'):
            try:
                if p['ModbusADUResponse'][1].funcCode == 1:
                    # r = reg_val_list_binary(s)
                    r = v.extend(p['ModbusADUResponse'][1].coilStatus)
                    for i in r:
                        if i == 1:
                            v.extend([1,0,0])
                        else:
                            v += [int(bit)
                    for bit in str( bin(i) )[2:].zfill(8)] [::-1]
            except AttributeError:
                pass
    return v 

Solution

This is the approach in order to convert a decimal number into binary.

binary_number = '0:05b'.format(int(decimal))

or if decimal_number not in string then directly do this.

binary_number = '0:05b'.format(decimal)

'0:05b', zero before colon concatenate zeros for example if there is 5 number of bits then binary of 5 = 01001 but with writing zero before colon gives 1001. and 05 after the colon describe the number of bits you want.



Answered By - Ali Hassan Ahmed Khan
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.