Concatenate numbers in binary [duplicate] - python

This question already has answers here:
Python int to binary string?
(36 answers)
Closed 6 years ago.
When converting a number in binary in Python what you get is the following:
b = bin(77)
print(b) # 0b1001101
When I was expecting 01001101. I am guessing that the b is there to let Python know that this is a binary number and not some integer. And that is ok within Python but what is considered safe practise here if you want to communicate with the outside world? This might be a silly example but online converters for instance do not recognise the above binary.
Would simply removing b always do the trick? Because I seem to be running into problems trying to code the Ascii85 encoder/decoder where concatenations of binary numbers take place. You can take a look at this example here.
My code is this case produces the following:
ch = 'Man '
list_ = [ord(x) for x in ch] # [77, 97, 110, 32]
binary_repr = ''.join(bin(x) for x in list_) # 0b10011010b11000010b11011100b100000
# When it should be 01001101011000010110111000100000
Notice that simply replacing the b with nothing doesn't quite cut it here. This is probably some dumm mistake but can someone clear things up for me?

>>> format(b, '08b')
Where b is your number and '08b' is the number of bit you want to use representing your number, if the parameter is #08b instead of 08b, you get the 0b in front of the number.
use format in every further operation and you should be good!

Doesn't
str(b)[2:]
do the job?
But you'll maybe better do:
"{0:b}".format(77)

Related

How to format Python code to always return this specific length [duplicate]

This question already has answers here:
Dynamically calculated zero padding in format string in python
(2 answers)
How do I pad a string with zeroes?
(19 answers)
Closed 9 months ago.
Sorry if this is a bit of a noob question. But moving on..
Say at the beginning of my code I set a variable, like this:
TestVar = 'A6'
But I later want it to print out as 000000A6
Or say it was
TestVar = 'C30'
I'd want it to print out as 00000C30
Basically always returning it with a length of 8
The reasoning for this is I've made a general script for modding a game, (I can link if asked) and you need to put in certain values which I want to have format automatically for ease of use. For example on running it'll print
Item ID Here:
And if you put in 166 it would convert the decimal number to hex which would be A6, however in order to be usable for all values (not just ones that are 2 digits once converted) I'm trying to make it detect it's length and format it with the 0s before.
Sorry if this doesnt make sense, in a simpler way of saying this, is there a way for it to detect the length of a variable? So for example in pseudo
TestVar = 'C30'
If TestVar length = 3
print('00000'+TestVar)
Print Result: 00000C30
Basically always returning it with a length of 8
That's what format strings do:
>>> print(f"{'C30':>08s}")
00000C30
As a sidenote, to output any number as 8-digit hex:
>>> print(f"{100:>08X}")
00000064
>>> print(f"{1024:>08X}")
00000400
See the documentation:
for f-strings (the f'I am an f-string' syntax);
for formatting syntax (the >08s and >08X thing).
Use string function rjust():
print(test.rjust(8,'0'))
The .zfill string method can be used.
For example:
s = 'C30'
s.zfill(8)
>>> '00000C30'
Try this code
txt = "A6"
x = txt.zfill(8)
print(x)
You can use string.zfill method
for example.
code = '3C0'
filledCode = code.zfill(8)
this method filled with zero the number of digit that you pass like a parameter
try something like this str.rjust() function
i = 1111
pad = '0'
n = 8
x = str(i).rjust(n, pad)
print(x) # 00001111

python - cut a x-bit binary number to a byte (8bit)

I am using python 2.7. I need to truncate a binary number from a x-bits to 8 bits (byte)
i will write an example of what i would like to do to make it clear and also because stackexchange doesn't leave me write my question for some reason, example:
0b1010101010100101 -> 0b10100101
i tried this workaround: converting it to string and then cutting it as a sub-string, but i didn't manage to make it working
str_cs = str(bin(cs))
str_cs = str_cs[to_cut:]
but i am facing many problem to convert it back to a binary number...
how would you truncate it?
Simply use a bitwise & with a byte of all 1s:
cs = cs & 0b11111111
# or, if you're feeling daring:
cs &= 0b11111111
Solution of Phydeaux much better but I was doing :
>>> cs=0b1010101010100101
>>> cs=int(bin(cs)[-8:], 2)
>>> bin(cs)
'0b10100101'
Based on what you were trying with str

Python - Convert intergers to floats within a string

I have an equation in the form of a string, something like this:
(20 + 3) / 4
I can easily solve this equation by using eval(), but it will give me an answer of 5, not the correct answer of 5.75. I know this is because 20, 3, and 4 are integers. So I was wondering, is there any way to just tack a .0 onto the end of them? Or is there some other trick I should use to make eval() think they are floats?
Note: the numbers will not always be integers, so it would be great if the solution could detect if they are integers and treat them accordingly.
Note #2: I'm using python 2.7
Note #3: I already know that "Python 2 is legacy, Python 3 is the future."
Thanks!
You could use sympy to parse the string using sympy_parser.parse_expr and then solve/simplify it:
>>> from sympy.parsing import sympy_parser
>>> exp = '(20 + 3) / 4'
>>> sympy_parser.parse_expr(exp).round(2)
5.75
This would also work for other valid mathematical expressions.

Strict Python formatting for floats

I'm using PYTHON to write to a file where the formatting is very strict. I have 10 available spaces in each column which cannot be exceeded.
I want to write the as many decimals as I can, but if the number is negative, the minus sign must be preferred over the last decimals. Also the period in the float must be counted into the number of available spaces. Numbers should be right trunctated
Example:
Let's say I want to print two numbers
a = 123.4567891011
b = 0.9876543210
Then I would want the result:
123.4567890.98765432
But if I now have the following:
a = -123.1111111111
b = 98765.432101234
c = 567
d = 0.1234
Then I'd want:
-123.1111198765.4321 567.0 0.1234
Would be to nice use exponential notation for high numbers, but not a necessity. I'm unable to find the answer. All I can find is to fix the format to number of significant digits, which really won't help me.
I've tried several methods of the
f.write({0:>10}{1:>10}.format(a,b))
but can't figure it out. Hope you see what I`m looking for.
Okay, so I found a way. I basically convert everything to strings and use:
f.write("{0:>10.10}{1:>10.10}".format(str(a),str(b)))
and so on..

What does the b mean in the return of python bin()? [duplicate]

This question already has answers here:
How to return a number as a binary string with a set number of bits in python
(3 answers)
Closed 7 years ago.
I am trying to convert hex to binary in python. I am using:
hexNumber = "0x3a81"
print bin(int(hexNumber,16))
The return I am getting for hexNumber = 0x3a81 is: 0b11101010000001
I believe the correct conversion is 0011101010000001
The return I am getting for hexNumber = 0x53f6 is: 0b101001111110110
I believe the correct conversion is 0101001111110110
What does the b mean? If I am trying to slice the first 5 bits of the binary number, do I ignore the b or count it towards the string length?
The 0b is like the 0x on your hexNumber; it's an indication that the number is in a certain base, specifically base 2. If you want the binary digits, just slice that part off.
0b is the prefix for a binary number. It means that Python knows it's a number, and is just showing you it in binary.

Categories

Resources