This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert an integer to binary without using the built-in bin function
This function receives as a parameter a number in base 10 and should return a list representing the same value expressed in binary as a list of bits, where the first element in the list is the most significant (leftmost) bit.
convert_10_to_2(11) should return [1, 0, 1, 1]
I cannot use the binary function or outside functions, so it has to be done in a more complicated way.
b = ''
while num > 0:
b = str(num % 2) + b
num >>= 1
return (b)
Okay I got my code finally up, okay I get '1011', but I need [1,0,1,1], I can't really use any functions such as bin(x) or binary_list. That has been what's taking this question so long.
You can initialize a list, then iterate through the string using a for loop and append the value to the list every iteration, like such.
binary_string = convert_10_to_2(11)
binary_list = []
for character in binary_string:
binary_list.append(int(character))
bin(X), x is the integer the function returns a binary string
MORE # python build in functions
This will work for both Python 2.x and 3.x:
list(map(int, '{:b}'.format(11)))
Replace 11 with other number, if you wish. Remove enclosing list call, if you do not need support for Python 3.x. Enclose it in function, if you really find it necessary.
Related
I can't quite find a solution for this.
Basically what I've done so far is created a string which represents the binary version of x amount of characters padded to show all 8 bits.
E.g. if x = 2 then I have 0101100110010001 so 8 digits in total. Now I have 2 strings of the same length which I want to XOR together, but python keeps thinking it's a string instead of binary. If I use bin() then it throws a wobbly thinking it's a string which it is. So if I cast to an int it then removes the leading 0's.
So I've already got the binary representation of what I'm after, I just need to let python know it's binary, any suggestions?
The current function I'm using to create my binary string is here
for i in origAsci:
origBin = origBin + '{0:08b}'.format(i)
Thanks in advance!
Use Python's int() function to convert the string to an integer. Use 2 for the base parameter since binary uses base 2:
binary_str = '10010110' # Binary string
num = int(binary_str, 2)
# Output: 150
Next, use the bin() function to convert the integer to binary:
binary_num = bin(num)
# Output: 0b10010110
Is there a built-in python function to count bit flip in a binary string? The question I am trying to solve is given a binary string of arbitrary length, how can I return the number of bit flips of the string. For example, the bit flip number of '01101' is 3, and '1110011' is 2, etc.
The way I can come up with to solve this problem is to use a for loop and a counter. However, that seems too lengthy. Is there a way I can do that faster? Or is there a built-in function in python that allows me to do that directly? Thanks for the help!
There is a very fast way to do that without any explicit loops and only using Python builtins: you can convert the string to a binary number, then detect all the bit flips using a XOR-based integer tricks and then convert the integer back to a string to count the number of bit flips. Here is the code:
# Convert the binary string `s` to an integer: "01101" -> 0b01101
n = int(s, 2)
# Build a binary mask to skip the most significant bit of n: 0b01101 -> 0b01111
mask = (1 << (len(s)-1)) - 1
# Check if the ith bit of n is different from the (i+1)th bit of n using a bit-wise XOR:
# 0b01101 & 0b01111 -> 0b1101 (discard the first bit)
# 0b01101 >> 1 -> 0b0110
# 0b1101 ^ 0b0110 -> 0b1011
bitFlips = (n & mask) ^ (n >> 1)
# Convert the integer back to a string and count the bit flips: 0b1011 -> "0b1011" -> 3
flipCount = bin(bitFlips).count('1')
This trick is much faster than other methods since integer operations are very optimized compare to a loop-based interpreted codes or the ones working on iterables. Here are performance results for a string of size 1000 on my machine:
ljdyer's solution: 96 us x1.0
Karl's solution: 39 us x2.5
This solution: 4 us x24.0
If you are working with short bounded strings, then there are even faster ways to count the number of bits set in an integer.
Don't know about a built in function, but here's a one-liner:
bit_flip_count = len([x for x in range(1, len(x0)) if x0[x] != x0[x-1]])
Given a sequence of values, you can find the number of times that the value changes by grouping contiguous values and then counting the groups. There will be one more group than the number of changes (since the elements before the first change are also in a group). (Of course, for an empty sequence, this gives you a result of -1; you may want to handle this case separately.)
Grouping in Python is built-in, via the standard library itertools.groupby. This tool only considers contiguous groups, which is often a drawback (if you want to make a histogram, for example, you have to sort the data first) but in our case is exactly what we want. The overall interface of this tool is a bit complex, but in our case we can use it simply:
from itertools import groupby
def changes_in(sequence):
return len(list(groupby(sequence))) - 1
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 1 year ago.
I'm studying python. And I'm a beginner.
Reading a book, I came to look at this code.
for num in range(101):
print('Hello ('+str(num)+')')
num = num + 1
It's the result of this code...
Hello (0)
Hello (1)
Hello (2)
.
.
.
Hello (99)
Hello (100)
Is the code below necessary?
print('Hello ('+str(num)+')')
I don't understand why there's +str(num)+.
You can't add an int (or a numeric) to a string. Thus, once you print a string (here 'Hello'), you only can add a string (or a char) to that word, so you use str(num) to convert num to a string.
num = 3
'Hello' + str(num) => 'Hello 3'
The function str() transforms num into a string. Then, the strings are concatenated using the + operator, and then printed.
A modern and elegant way to do this would be to use f-strings:
for num in range(101):
print(f'Hello ({num})')
will produce the same result.
Side-note : you do not need to do num = num + 1 : num is already automatically incremented in the for loop.
Python, internally, keeps track of your types, which means that the types you use are tracked by python itself without you needing to explicitly declare them. What you are doing by using print('Hello ('+str(num)+')') is saying to the computer: "print on the screen the following value";
but since there is no sum operation between strings and numbers, you need to convert your number into a string, which is what you are doing by using str(num).
This constructs for you a string from the given number; so what you are doing is practically making the value 3 as a number become the value '3' as a string;
then the previous line of code, when num == 3, is equivalent to:
print('Hello (' + '3' + ')' )
which of course now is about a bunch of operations between strings, that are now accepted; here is some more information about python's types handling.
Also, check the answer by Louis-Justin Tallot which provides a solution using f-strings (where f stands for format) that allows you to use the f'{variableName}' syntax, evaluating the value between the curly brackets directly to a string.
I have a list/array of numbers, which I want to save to a binary file.
The crucial part is, that each number should not be saved as a pre-defined data type.
The bits per value are constant for all values in the list but do not correspond to the typical data types (e.g. byte or int).
import numpy as np
# create 10 random numbers in range 0-63
values = np.int32(np.round(np.random.random(10)*63));
# each value requires exactly 6 bits
# how to save this to a file?
# just for debug/information: bit string representation
bitstring = "".join(map(lambda x: str(bin(x)[2:]).zfill(6), values));
print(bitstring)
In the real project, there are more than a million values I want to store with a given bit dephts.
I already tried the module bitstring, but appending each value to the BitArray costs a lot of time...
The may be some numpy-specific way that make things easier, but here's a pure Python (2.x) way to do it. It first converts the list of values into a single integer since Python supports int values of any length. Next it converts that int value into a string of bytes and writes it to the file.
Note: If you're sure all the values will fit within the bit-width specified, the array_to_int() function could be sped up slightly by changing the (value & mask) it's using to just value.
import random
def array_to_int(values, bitwidth):
mask = 2**bitwidth - 1
shift = bitwidth * (len(values)-1)
integer = 0
for value in values:
integer |= (value & mask) << shift
shift -= bitwidth
return integer
# In Python 2.7 int and long don't have the "to_bytes" method found in Python 3.x,
# so here's one way to do the same thing.
def to_bytes(n, length):
return ('%%0%dx' % (length << 1) % n).decode('hex')[-length:]
BITWIDTH = 6
#values = [random.randint(0, 2**BITWIDTH - 1) for _ in range(10)]
values = [0b000001 for _ in range(10)] # create fixed pattern for debugging
values[9] = 0b011111 # make last one different so it can be spotted
# just for debug/information: bit string representation
bitstring = "".join(map(lambda x: bin(x)[2:].zfill(BITWIDTH), values));
print(bitstring)
bigint = array_to_int(values, BITWIDTH)
width = BITWIDTH * len(values)
print('{:0{width}b}'.format(bigint, width=width)) # show integer's value in binary
num_bytes = (width+8 - (width % 8)) // 8 # round to whole number of 8-bit bytes
with open('data.bin', 'wb') as file:
file.write(to_bytes(bigint, num_bytes))
Since you give an example with a string, I'll assume that's how you get the results. This means performance is probably never going to be great. If you can, try creating bytes directly instead of via a string.
Side note: I'm using Python 3 which might require you to make some changes for Python 2. I think this code should work directly in Python 2, but there are some changes around bytearrays and strings between 2 and 3, so make sure to check.
byt = bytearray(len(bitstring)//8 + 1)
for i, b in enumerate(bitstring):
byt[i//8] += (b=='1') << i%8
and for getting the bits back:
bitret = ''
for b in byt:
for i in range(8):
bitret += str((b >> i) & 1)
For millions of bits/bytes you'll want to convert this to a streaming method instead, as you'd need a lot of memory otherwise.
I am tasked with writing a function that takes a string of arbitrary length of Binary in the Two's Compliment system, and return the corresponding integer in base 10. I can not use for or while loops, and I can't use built in converting functions. I can use recursion.
I have written a helper function that takes the first digit in a string of binary and finds what value in base 10 this would add to the sum, I've copied it below.
def first(str):
'''this program finds the value in base 10 of the 0th digit in a string of binary'''
n=len(str)
return int(str[0])*(2**(n-1))
I need help with the handling of negative numbers, as well as the formatting of the overall function.
Thanks!
def bin(s):
return 0 if not s else 2*bin(s[:-1]) + int(s[-1])
convert_2_to_decimal = lambda s: bin(s[1:]) - int(s[0])*2**(len(s)-1)