PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

[FIXED] How to convert ASCII to Bit string (binary)

 August 11, 2022     ascii, binary, decimal, python     No comments   

Issue

I'm looking for a loop similar to this for converting ASCII to decimal then decimal to binary string: string = input("Enter message: ")

#Convert string from ASCII to Decimal
A_string = [ord(c) for c in string]
print(A_string)

# add 1 to ASCII value 
B_string = A_string
for i in range(len(B_string)):
    B_string[i] = B_string[i] + 1 
print(B_string)


#Decimal to Binary
decimal = B_string
remainder = decimal
Binary_string = decimal

for i in range(len(decimal)):
    remainder[i] = int(decimal[i])
    remainder[i] %= 2
    decimal[i] = decimal[i] // 2
    Binary_string[i] = str(remainder[i] + Binary_string[i])
print(Binary_string)

What I'm NOT looking for are things like this:

res = "".join(f"{ord(shiftedChar):08b}")

shiftedChar

I'm looking for BASIC OLD SCHOOL techniques... programming what's actually happening using basic division, multiplication, powers, etc


Solution

From https://stackoverflow.com/a/7397195/1675501

First, you need to strip the 0b prefix, and left-zero-pad the string so it's length is divisible by 8, to make dividing the bitstring up into characters easy:

bitstring = bitstring[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring

Then you divide the string up into blocks of eight binary digits, convert them to ASCII characters, and join them back into a string:

string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8))
string = ''.join(chr(int(char, 2)) for char in string_blocks)

If you actually want to treat it as a number, you still have to account for the fact that the leftmost character will be at most seven digits long if you want to go left-to-right instead of right-to-left.



Answered By - Rusty Robot
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing