How to append \ join binary digits to a variable - python

How can i append binary digits to a final variable in python
a = self.allcheckboxes[0].isChecked() # 1
b = self.allcheckboxes[1].isChecked() # 0
c = self.allcheckboxes[2].isChecked() # 1
d = self.allcheckboxes[3].isChecked() # 0
final_value = 010+a+b+c+d
# iam expecting something like 0101010 in binary

I am assuming you just want a binary looking string, rather than an integer with the relevant bits set, if so you could use the following for checkboxes 10 to 14:
final_value = ''.join('1' if checkbox.isChecked() else '0' for checkbox in self.allcheckboxes[10:15])
This could then be converted to an integer and printed as hex if required as follows:
integer_value = int(final_value, 2)
print '{:x}'.format(integer_value)

You can use operator.itemgetter and operator.attrgetter within map function to do all the codes in one line and use str.join() to join the result :
from operator import itemgetter,attrgetter
''.join(map(attrgetter('isChecked'),itemgetter(0,1,2,3)(self.allcheckboxes)))
Also note that there is no binary type in python, when you get the concatenated string, based on your aim and the functions which you are dialing for, you can tread with this string as a binary number.
For example if you want to convert it to an integer you can use int function by passing 2 as its base:
>>> int('0101',2)
5

Related

Making a function to manipulate an integer

I want to make a function to transform an integer.
For example:
d = "1209834"
I want to , in one function, turn it into an integer, then turn it into a binary, then strip off the 0b prefix. So I'd just get 100100111010111101010 as a result when the function is applied.
Can use built-in bin and int
>>> bin(int(d))[2:]
'100100111010111101010'
You can do this in one line:
d = "1209834"
int_d = int(d)
binary_d = "{0:b}".format(int_d) # binary of d as a string

How to convert hexadecimal string to character with that code point?

I have the string x = '0x32' and would like to turn it into y = '\x32'.
Note that len(x) == 4 and len(y) == 1.
I've tried to use z = x.replace("0", "\\"), but that causes z = '\\x32' and len(z) == 4. How can I achieve this?
You do not have to make it that hard: you can use int(..,16) to parse a hex string of the form 0x.... Next you simply use chr(..) to convert that number into a character with that Unicode (and in case the code is less than 128 ASCII) code:
y = chr(int(x,16))
This results in:
>>> chr(int(x,16))
'2'
But \x32 is equal to '2' (you can look it up in the ASCII table):
>>> chr(int(x,16)) == '\x32'
True
and:
>>> len(chr(int(x,16)))
1
Try this:
z = x[2:].decode('hex')
The ability to include code points like '\x32' inside a quoted string is a convenience for the programmer that only works in literal values inside the source code. Once you're manipulating strings in memory, that option is no longer available to you, but there are other ways of getting a character into a string based on its code point value.
Also note that '\x32' results in exactly the same string as '2'; it's just typed out differently.
Given a string containing a hexadecimal literal, you can convert it to its numeric value with int(str,16). Once you have a numeric value, you can convert it to the character with that code point via chr(). So putting it all together:
x = '0x32'
print(chr(int(x,16)))
#=> 2

The int function and its parameters

I'm working on this series of problems.
I do not understand question 11 and the way int() is being used. I understand that converting x directly into an int causes the loss of some zeroes so doing that was out of the question but I'm not understanding what
intp = int(p,2)
is suppose to be doing. Printing out intp I get the following values, 4,3,10,9. How is that at all related to 0100,0011,1010,1001? Also why are zeros lost in the first place?
Question 11
Level 2
Question: Write a program which accepts a sequence of comma separated
4 digit binary numbers as its input and then check whether they are
divisible by 5 or not. The numbers that are divisible by 5 are to be
printed in a comma separated sequence.
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.
Hints: In case of input data being supplied to the question, it should
be assumed to be a console input.
value = []
items=[x for x in raw_input().split(',')]
for p in items:
print p
intp = int(p, 2)
print intp
if not intp%5:
value.append(p)
print ','.join(value)
To convert binary number into Decimal, we have to use the python built-in int function, which takes the binary number and the base of number system as an argument.
Example:
>>> p='1010'
>>> c=int(p,2)
>>> print c
10
int() function in Python and Python3 converts a number in a given base to decimal.
Syntax :int(string, base)
Parameter :
string: consists of 1's and 0's
base : (integer value) base of the number.
Returns :
Returns an integer value, which is equivalent
of binary string in the given base.
for more information Click here
As the grumpy comments up above suggested, the int function takes a second argument, which is the base of the conversion. So it's taking the base 2 (binary) variable bound to p and turning it to a base-10 int, i.e., normal human.
value = []
items=[x for x in input().split(',')]
for p in items:
intp = int(p, 2)
value.append(intp)
for x in value:
if x%5==0:
print(bin(x))

Length of hexadecimal number

How can we get the length of a hexadecimal number in the Python language?
I tried using this code but even this is showing some error.
i = 0
def hex_len(a):
if a > 0x0:
# i = 0
i = i + 1
a = a/16
return i
b = 0x346
print(hex_len(b))
Here I just used 346 as the hexadecimal number, but my actual numbers are very big to be counted manually.
Use the function hex:
>>> b = 0x346
>>> hex(b)
'0x346'
>>> len(hex(b))-2
3
or using string formatting:
>>> len("{:x}".format(b))
3
While using the string representation as intermediate result has some merits in simplicity it's somewhat wasted time and memory. I'd prefer a mathematical solution (returning the pure number of digits without any 0x-prefix):
from math import ceil, log
def numberLength(n, base=16):
return ceil(log(n+1)/log(base))
The +1 adjustment takes care of the fact, that for an exact power of your number base you need a leading "1".
As Ashwini wrote, the hex function does the hard work for you:
hex(x)
Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression.

Why do I have to convert numbers into strings to get its location?

Why will it not print out the position of a integer/float until I have converted it to a string?
example
x = 123
print x[0] # error
To fix this I have to do
x = 123
print str(x)[0]
But why do I have to make it into a string for it to work?
Well, why should this work in the first place? What is the nth index of a number; what is index 0 of the decimal number 123?
Is it 1 because of its decimal representation?
Is it 7 because of its hexadecimal representation (7B)?
Is it 0 because of its hexadecimal representation (0x7B)?
Is it 1 because of its octal representation (173)?
Is it 0 because of its octal representation (0173)?
Is it 1 because of its binary representation (1111011)
Is it 1 because of its binary representation with the least significant bit first (1101111)?
Is it S because that’s what 123 is in ASCII?
…
As you can see, this is very unclear, and it does not make sense to begin with. When using the index access on a list, you get the nth element of the list. When you use the index access on a sequence, you get the nth element of the sequence. A string is a sequence of characters, so when using the index access on a string, you get the nth element of the string sequence; the nth character. A number is no sequence, only its string representation in some format is.
123 is but one representation of the integer value. Python int values are not sequences or mappings, so [item] indexing has no meaning for them.
By turning the number into a string, you 'capture' the representation into a series of digit characters and you then can get the first one.
Another way to do it would be to divide by 10 until you have a number lower than 10:
x = 123
while x > 10:
x //= 10
print x # prints the number 1
Note that x then holds an int still, not a single-character string.
The simple answer is because you have the wrong type. Integers don't support indexing -- and I really don't think they should (they're not sequences or mappings and I can't think of any way that indexing an integer actually makes sense).
Note that there is more than one way to represent an integer as well:
>>> 0x7b == 123
True
So in this case, who is to say that x[0] should return 1 instead of 0 (or 7) depending on how you want to think of it?
As a side note to the excellent answers above, this is one way you can convert a number to a list of numbers to allow indexing:
In [2]: map(int,str(123))
Out[2]: [1, 2, 3]
In [3]: map(int,str(123))[0]
Out[3]: 1
In [4]: type(map(int,str(123))[0])
Out[4]: int

Categories

Resources