PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

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

 August 10, 2022     binary, data-conversion, decimal, list, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing