Binary to Corresponding Ascii String Conversion

Binary To Corresponding ASCII String Conversion

This should do the trick... or at least get you started...

public Byte[] GetBytesFromBinaryString(String binary)
{
var list = new List<Byte>();

for (int i = 0; i < binary.Length; i += 8)
{
String t = binary.Substring(i, 8);

list.Add(Convert.ToByte(t, 2));
}

return list.ToArray();
}

Once the binary string has been converted to a byte array, finish off with

Encoding.ASCII.GetString(data);

So...

var data = GetBytesFromBinaryString("010000010100001001000011");
var text = Encoding.ASCII.GetString(data);

converting binary to corresponding ASCII character

For your code, you can't use "strtol" without a twist. The char array that you give to "strtol" may not end with "\0". Also, does not matter what you do your array will always have 12 indexes unless you copy a "\0" to index 9 so that "strtol" know that it is the end of the input.

Also, sometimes loops are not the best. For your case, you already know how many indexes you are working with. There is no point in using a loop. Nonetheless, I wrote two methods and included the test code as an example below.

#include <stdio.h>

/*
* This function generate a hammer binary digit string for testing.
* It does not care about the validity of the hammer bit.
* The array that is passed to this function should be the length of 12.
*/

void generateChar(int value, char * output){
output[0] = '0';
output[1] = '0';
output[3] = '0';
output[7] = '0';
output[2] = (value & 0b10000000) > 0? '1' : '0';
output[4] = (value & 0b01000000) > 0? '1' : '0';
output[5] = (value & 0b00100000) > 0? '1' : '0';
output[6] = (value & 0b00010000) > 0? '1' : '0';
output[8] = (value & 0b00001000) > 0? '1' : '0';
output[9] = (value & 0b00000100) > 0? '1' : '0';
output[10] = (value & 0b00000010) > 0? '1' : '0';
output[11] = (value & 0b00000001) > 0? '1' : '0';
}

/*
* First method.
*
*/
char charToBin(char usersInput[]) {
char c = 0;
c = usersInput[2] == '1'? c | 0b10000000 : c;
c = usersInput[4] == '1'? c | 0b01000000 : c;
c = usersInput[5] == '1'? c | 0b00100000 : c;
c = usersInput[6] == '1'? c | 0b00010000 : c;
c = usersInput[8] == '1'? c | 0b00001000 : c;
c = usersInput[9] == '1'? c | 0b00000100 : c;
c = usersInput[10] == '1'? c | 0b00000010 : c;
c = usersInput[11] == '1'? c | 0b00000001 : c;

return c;
}

/*
* Second method.
*/
char charToBin2(char usersInput[]) {
char temp[9];
int pos = 0;
temp[8] = '\0'; // Protect from overflow.

for ( int i = 2; i < 12; i++ ){
if ( i == 3 || i == 7 ) continue;
temp[pos] = usersInput[i];
pos++;
}

return (char) strtol(temp, (char **)NULL, 2);
}

int main(){
char a[] = "100010010001";
char t[12];
int b;

// Test for method 1
for ( int i = 0; i < 256; i++ ){
generateChar(i, t);
b = charToBin(t);
printf("%d ", (unsigned char) b );
}

printf("\n\n");

// Test for method 2
for ( int i = 0; i < 256; i++ ){
generateChar(i, t);
b = charToBin2(t);
printf("%d ", (unsigned char) b );
}

return 0;
}

Convert binary to ASCII and vice versa

For ASCII characters in the range [ -~] on Python 2:

>>> import binascii
>>> bin(int(binascii.hexlify('hello'), 16))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> binascii.unhexlify('%x' % n)
'hello'

In Python 3.2+:

>>> bin(int.from_bytes('hello'.encode(), 'big'))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
'hello'

To support all Unicode characters in Python 3:

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
n = int(bits, 2)
return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0'

Here's single-source Python 2/3 compatible version:

import binascii

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
n = int(bits, 2)
return int2bytes(n).decode(encoding, errors)

def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

Example

>>> text_to_bits('hello')
'0110100001100101011011000110110001101111'
>>> text_from_bits('110100001100101011011000110110001101111') == u'hello'
True

Binary String to ASCII TEXT String

first translate the binary string into a byte[] using How could I encode a string of 1s and 0s for transport?

next use the Convert.ToBase64String method to get the actual System.String

Printing out binary ASCII code for a character string in C

You declared b as a array of struct so if you print the value of b it will give you the base address of array.

Use loop to print the array values.

You are using w to get the binary value but the input is in wordd[] did you copy the value ?

How exactly does binary code get converted into letters?

Assuming that by "binary code" you mean just plain old data (sequences of bits, or bytes), and that by "letters" you mean characters, the answer is in two steps. But first, some background.

  • A character is just a named symbol, like "LATIN CAPITAL LETTER A" or "GREEK SMALL LETTER PI" or "BLACK CHESS KNIGHT". Do not confuse a character (abstract symbol) with a glyph (a picture of a character).
  • A character set is a particular set of characters, each of which is associated with a special number, called its codepoint. To see the codepoint mappings in the Unicode character set, see http://www.unicode.org/Public/UNIDATA/UnicodeData.txt.

Okay now here are the two steps:

  1. The data, if it is textual, must be accompanied somehow by a character encoding, something like UTF-8, Latin-1, US-ASCII, etc. Each character encoding scheme specifies in great detail how byte sequences are interpreted as codepoints (and conversely how codepoints are encoded as byte sequences).

  2. Once the byte sequences are interpreted as codepoints, you have your characters, because each character has a specific codepoint.

A couple notes:

  • In some encodings, certain byte sequences correspond to no codepoints at all, so you can have character decoding errors.
  • In some character sets, there are codepoints that are unused, that is, they correspond to no character at all.

In other words, not every byte sequence means something as text.

How to convert a binary String to Original String

str_data='Hi'
binarystr = ''.join(format(ord(x),'b') for x in str_data)
String=''
for i in range(0,len(binarystr),7):
String+=chr(int(binarystr[i:i+7],2))
print(String)

Convert stringbinary to ascii

The simple solution,

using SubString and built in Convert.ToByte could look like this:

string input = "0110100001100101011011000110110001101111";
int charCount = input.Length / 8;
var bytes = from idx in Enumerable.Range(0, charCount)
let str = input.Substring(idx*8,8)
select Convert.ToByte(str,2);
string result = Encoding.ASCII.GetString(bytes.ToArray());
Console.WriteLine(result);

Another solution, doing the calculations yourself:

I added this in case you wanted to know how the calculations should be performed, rather than which method in the framework does it for you:

string input = "0110100001100101011011000110110001101111";
var chars = input.Select((ch,idx) => new { ch, idx});
var parts = from x in chars
group x by x.idx / 8 into g
select g.Select(x => x.ch).ToArray();

var bytes = parts.Select(BitCharsToByte).ToArray();
Console.WriteLine(Encoding.ASCII.GetString(bytes));

Where BitCharsToByte does the conversion from a char[] to the corresponding byte:

byte BitCharsToByte(char[] bits) 
{
int result = 0;
int m = 1;
for(int i = bits.Length - 1 ; i >= 0 ; i--)
{
result += m * (bits[i] - '0');
m*=2;
}
return (byte)result;
}

Both the above solutions does basically the same thing: First group the characters in groups of 8; then take that sub string, get the bits represented and calculate the byte value. Then use the ASCII Encoding to convert those bytes to a string.



Related Topics



Leave a reply



Submit