1

I was trying to read some values from an XML file, say the values represent the reset state of a hardware register. The <Field_Reset_Value>10</Field_Reset_Value> represent two bits here as "1" and "0" respectively. I need to use these values to shift and bitwise or with other bit values further.

Now when I read the value, it is represented as a string. Can someone suggest the way, I can convert string to binary. Say as the example below.

string = "10"

Now I want to convert its binary value as binval = 0b10.

Also, these values can be of any number of bits from 1 to 32 bit. What I mean is the string can also be 1101001110011 so I will need to represent it as 0b1101001110011

GeoSn0w
  • 684
  • 1
  • 9
  • 20
sandeep
  • 141
  • 1
  • 1
  • 11
  • `int('10', 2)` will give you the integer `2`. `bin(int('10', 2))` will give you the string `"0b10"`. Likewise `int('1101001110011', 2)` gives the integer `6771` – Mark Oct 19 '21 at 03:44
  • Hey thanks Mark. I missed converting it to integer with base 2, so I was getting different results. This helps. – sandeep Oct 19 '21 at 05:09

1 Answers1

0

You can use the following code:

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574