How to Convert String to Binary

How to convert string to binary?

Something like this?

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

Golang: How to convert String to binary representation

This is a simple way to do it:

func stringToBin(s string) (binString string) {
for _, c := range s {
binString = fmt.Sprintf("%s%b",binString, c)
}
return
}

As I included in a comment to another answer you can also use the variant "%s%.8b" which will pad the string with leading zeros if you need or want to represent 8 bits... this will however not make any difference if your character requires greater than 8 bit to represent, such as Greek characters:

Φ 1110100110

λ 1110111011

μ 1110111100

Or these mathematical symbols print 14 bits:

≠ 10001001100000

⊂ 10001010000010

⋅ 10001011000101

So caveat emptor: the example herein is meant as a simple demonstration that fulfills the criteria in the original post, not a robust means for working with base2 representations of Unicode codepoints.

How to convert text to binary code in JavaScript?

What you should do is convert every char using charCodeAt function to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2):

HTML:

<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>

JS:

function convert() {
var output = document.getElementById("ti2");
var input = document.getElementById("ti1").value;
output.value = "";
for (var i = 0; i < input.length; i++) {
output.value += input[i].charCodeAt(0).toString(2) + " ";
}
}

And here's a fiddle: http://jsfiddle.net/fA24Y/1/

Convert Binary String to Binary

Use this:

    System.out.println(Integer.toBinaryString(Integer.parseInt("000",2))); // gives 0
System.out.println(Integer.toBinaryString(Integer.parseInt("010",2))); // gives 10
System.out.println(Integer.toBinaryString(Integer.parseInt("100",2))); // gives 100

JAVA converting from String to Binary and then back to String in file

I didnt go into detail on how to read/write files, since you can look that up. However, to achieve what you want:

  • you will need a method to convert a word to binary
  • then you will need another method to convert from binary to words

below is the code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class HelloWorld{

public static void main(String []args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner sc = new Scanner(file);
String word=sc.nextLine();
String receivedBinary=stringToBinary(word);
System.out.println();
String receivedWord=BinaryToString(receivedBinary);
}
public static String stringToBinary(String text)
{
String bString="";
String temp="";
for(int i=0;i<text.length();i++)
{
temp=Integer.toBinaryString(text.charAt(i));
for(int j=temp.length();j<8;j++)
{
temp="0"+temp;
}
bString+=temp+" ";
}

System.out.println(bString);
return bString;
}
public static String BinaryToString(String binaryCode)
{
String[] code = binaryCode.split(" ");
String word="";
for(int i=0;i<code.length;i++)
{
word+= (char)Integer.parseInt(code[i],2);
}
System.out.println(word);
return word;
}
}

How to convert string to binary

It sounds like you are looking for the Dart equivalents of javascript's String.charCodeAt method. In Dart there are two options depending on whether you want to the character codes for the whole string or just a single character within the string.

  • https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.String#id_codeUnitAt
  • https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.String#id_codeUnits

String.codeUnitAt is a method that returns an int for the character at a given index in the string. You use it as follows:

String str = 'hello';
print(str.codeUnitAt(3)); //108

You can use String.codeUnits to convert the entire string into their integer values:

String str = 'hello';
print(str.codeUnits); //[104, 101, 108, 108, 111]

If you need to then convert those integers into their corresponding binary strings you'll want to us int.toRadixString with an argument of 2

String str = 'hello';
List<String> binarys = str.codeUnits.map((int strInt) => strInt.toRadixString(2));
print(binarys); //(1101000, 1100101, 1101100, 1101100, 1101111)

Convert a String to binary in swift?

Use func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?

Example:

Swift 5

let string = "The string"
let binaryData = Data(string.utf8)

Swift 3

let string = "The string"
let binaryData: Data? = string.data(using: .utf8, allowLossyConversion: false)

EDIT: Or wait, do you need binary representation of you data or string of 0/1?

EDIT:
For string of 0/1 use something like:

let stringOf01 = binaryData?.reduce("") { (acc, byte) -> String in
acc + String(byte, radix: 2)
}

EDIT: Swift 2

let binaryData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)


Related Topics



Leave a reply



Submit