Thread: Printing a Binary formatted number Help!!

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2013
Posts
5
Rep Power
0

Printing a Binary formatted number Help!!

I am a definite newbie to Python ( but not necessarily to programming, have used C and machine code, but still trying to get my head around some of the syntax to get something running ),..
(I am using python 3.3 )

I wish to use a 48 bit wide binary number of the format 0b010100....10101 ( 48bits wide )
(I am using python 3.3 )

and print a line of ASCII text, formatted thus with 6 HEX numbers in the string:-
s AA 00 - A5 55 - 00 40 = 01;

As a conversion,.. ( from the 48 bit binary number,.. just the middle bank of 6 digits), the other number/characters come from else where....
Having trouble on best method and the "best way" to approach with my limited knowledge.
Many thanks
2. The ideas you need might be found in this session:
Code:
```>>> import random
>>> BINARY_STRING = [random.choice('01') for i in range(48)]
>>> ''.join(BINARY_STRING)
'011001010100100111100010001110011000110111100000'
>>> N = int(''.join(BINARY_STRING), 2) # convert to integer using base 2
>>> N
111368002440672
>>> S = (('0'*12)+'{:x}'.format(N))[-12:]
>>> print(S)
6549e2398de0
>>> RESULT = [S[i:i+2] for i in range(0,len(S),2)]
>>> print(RESULT)
['65', '49', 'e2', '39', '8d', 'e0']
>>>
>>>
>>> [S[i:i+2] for i in reversed(range(0,len(S),2))]
['e0', '8d', '39', 'e2', '49', '65']```
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2013
Posts
5
Rep Power
0
Many thanks,..
will probably get back to you with some more questions ( if thats OK ),.. but need to get my head around this first...
and see if I can make it tick....

but many thanks for taking the time to respond
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2013
Posts
5
Rep Power
0
OK ,.. I'm working through bit by bit.....I have got

def lit():
import random
BINARY_STRING = [random.choice('01') for i in range(48)]
''.join(BINARY_STRING)
print ("%s" % BINARY_STRING)
# print ("%s" join(BINARY_STRING)) --- Fails!! join is a function, not the string
N = int(''.join(BINARY_STRING), 2) # convert to integer using base 2
print ("%d" % N)

would you mid helping me improve my understanding,... I am sure these are pretty dumb questions to an expert,.. ( but alas I cannot put myself in that category )

I see the 1st couple of lines create a random string with zeros and ones,... into string BINARY_STRING,....
why can I not print complete string? join in the function to concatenate it together,.. so I am sure this is wrong but don't know which is the correct way as I don't understand the line:-
N = int(''.join(BINARY_STRING), 2)
and how the '' is used relevant. I see this is converting to an integer base 10 using the string as a base 2 number.

I see this is converting to an int type,.. (base 10 ), but I require to play/manipulate a binary number,... of the format 0b010101010 as I know I can rotate this easily at the bit level with "N << 2"

Haven't gone much further with code but see code then converts string to Integer(base 10), then converts to hex,.. although I don't see how this happens as there is no base referenced as far as I can see,.. can you give me some pointers here pls...

Lots of questions,... hope you can help
Many thanks
5. I don't understand your original question completely. I assumed that you have a bit string of length forty-eight and want to convert it to twelve hexadecimal digits (one per nibble) in groups of 2 (representing the usual eight bit byte).
Code:
```'''
Example run: \$ python3 thisfile.py

Some examples:
binary string 0b000010110111101101010100111110001010111000111100
as hexadecimal ['0b', '7b', '54', 'f8', 'ae', '3c']

binary string 0b011100010111000100111010110100100110010101011001
as hexadecimal ['71', '71', '3a', 'd2', '65', '59']

binary string 0b101100100100001010111101010101100010010100101001
as hexadecimal ['b2', '42', 'bd', '56', '25', '29']

binary string 0b111010001010011101110101010111010101001110001011
as hexadecimal ['e8', 'a7', '75', '5d', '53', '8b']

Which I confirm in j.  www.jsoftware.com.
,/"2@:(_ 3 {. _2 [\ '0123456789abcdef' {~ _12 {. 16 #.inv ])"0] 2b000010110111101101010100111110001010111000111100  2b011100010111000100111010110100100110010101011001 2b101100100100001010111101010101100010010100101001 2b111010001010011101110101010111010101001110001011
0b 7b 54 f8 ae 3c
71 71 3a d2 65 59
b2 42 bd 56 25 29
e8 a7 75 5d 53 8b

Guess which program took longer to write?  Was it
,/"2@:(_ 3 {. _2 [\ '0123456789abcdef' {~ _12 {. 16 #.inv ])"0]

or--->
'''

def convert_to_list_of_hex_strings(n, bytes):
'''
convert n to hexadecimal representation string,
group into bytes groups,
and return the list.
Note that the order in resulting list has bytes of decreasing significance.
bugs: does not handle negative n
'''
A = '{:x}'.format(n) # string format to create lower case hexadecimal
# http://docs.python.org/3/library/string.html#format-specification-mini-language
assert set(A).issubset(set('01234567889abcdef012323432434534545634545645766587768609abcdef')) # not too convincing, huh.
assert type(A) is str
B = ('00'*bytes) + A     # assuming n was 0 or small, B is padded.  This is probably possible directly using the aforereferenced incomprehensible string formatting mini-language.
C = B[-2*bytes:] # http://docs.python.org/3/tutorial/introduction.html#lists
D = []
for i in range(bytes):
j = 2*i
D.append(C[j:j+2])
assert len(D) == bytes
return D

def convert_bit_string_to_list_of_hex(BS):
assert type(BS) is str
assert BS[:2] == '0b'          # first two characters of BS are 0b
assert 2 < len(BS)
n = int(BS[2:], 2)
return convert_to_list_of_hex_strings(n, 48//8)

if __name__ == '__main__':

import random

def make_a_binary_string(bits = 48):
'''
This function returns a binary string of the form
'0b01..' (0b followed by bits number of zeros and ones)
If you already have a binary string then you do not
this function.  It merely creates data for examples.
'''
A = [random.choice('01') for i in range(bits)]
assert type(A) is not str
assert type(A) is list # A is a list, not a string.  A is not correct
B = ''.join(A)         # join is a METHOD of str, not a function
assert type(B) is str                      # B is now a string.
assert set(B).issubset(set('01'))          # B contains binary digits
assert len(B) == bits    # B is the correct length
C = '0b' + B             # prepend 0b.  2b makes a lot more sense.
assert len(C) == bits + 2
return C                 # return the value

def main():
print('Some examples:')
for i in range(4):
A = make_a_binary_string(bits = 48)
print(' binary string', A)
print()

main()```
6. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2013
Posts
5
Rep Power
0
many thanks,.. just digesting what you have sent,..

but can see some confusion with how I have typed things,...

0b10100101 is the binary number "10100101"
similiar to
0xEF,... a HEX number
so I do not need the "0b" prefix,... I assumed this was standard notation to denote a binary number,.. sorry my misunderstanding.

...thus having the 48bit string as a "binary number" I will look to shift it left and right using ">> 1" "<< 1" commands.

to explain what I am trying to do,... is create a text file with 6 x 8 bit bytes,.. these will represent individual light strings,.. I have built a small controller box based on a 6502 type ( actually 65816 ) processor,.. old I know,.. and have programmed it to read text files of the format
Pattern: Quick Shuffle P1;
.L0;
S FF 00 - FF 00 - FF 00 = 05;
S 00 00 - 00 00 - 00 00 = 05;
S 00 00 - 00 00 - 00 01 = 05;
S 00 00 - 00 00 - 00 02 = 05;
S 00 00 - 00 00 - 00 04 = 05;
S 00 00 - 00 00 - 00 08 = 05;

to represent light changes sequences....
All Characters in uppercase

I can read numerous files 256 max,. each with a different sequence,.. all I need are some pattern files,... hence my quest to create some bit pattern text files,.. fyi the start character of each line determines how the transition is handled,.. or if a block is repeated, and the final number is for how long that sequence is valid,... once I can create some basic patterns I can develop more,.. its just getting to that first hurdle,.. does that help.
One last thing the first character is followed by a TAB whilst others are SPACE characters...

Many thanks and Kind Regards
7. python_tab = '\t'
not_a_python_tab = r'\t'
python_space = ' '
python_any_ascii_character = '%c'%8 # tab I think
8. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2013
Posts
5
Rep Power
0
many thanks for your contribution,.. and feedback,.. and as you may have expected,.. you code was not the perfect answer to my problem,... Initially I looked at it and had an OMG moment I don't understand diddle squat here,...

However,.. after reviewing some more web sites,.. watching some more videos,.. your code now makes sense to me and I am using parts of it to achieve the result I wanted.
Still need to get my head round some of the "format" command string stuff,.. but there are plenty of examples out there,.. and I certainly have some more learning to do,.. but then we are always learning new things eh...

But once again thanks for contribution
Regards