Fastest Way to Convert String to Binary

Fastest way to Convert String to Binary?

Using std::bitset would work:

#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
string myString = "Hello World";
for (std::size_t i = 0; i < myString.size(); ++i)
{
cout << bitset<8>(myString.c_str()[i]) << endl;
}
}

Output:

01001000
01100101
01101100
01101100
01101111
00100000
01010111
01101111
01110010
01101100
01100100

Fastest Way to convert a Binary String to Binary Array (Array of 1 and 0)

bytearray appears to be even faster than Andrej's NumPy solution. And bytes can be used for a fast list solution. Times with 1024 bits (only showing the first 5):

f1   2.7 μs  [1 0 1 1 1]
f2 2.0 μs bytearray(b'\x01\x00\x01\x01\x01')
f3 7.6 μs [1, 0, 1, 1, 1]

Code based on Andrej's (Try it online!):

import numpy as np
from timeit import timeit

s = "1011" * 256 # length = 1024

def f1():
return np.frombuffer(s.encode("ascii"), dtype="u1") - 48

table = bytearray.maketrans(b'01', b'\x00\x01')

def f2():
return bytearray(s, "ascii").translate(table)

def f3():
return [*s.encode().translate(table)]

for _ in range(3):
for f in f1, f2, f3:
t = timeit(f, number=1_000)
t = '%5.1f μs ' % (t * 1e3)
print(f.__name__, t, f()[:5])
print()

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'

Converting a string into binary and back

There is a problem with your stringToBinary function. Converting a character to binary only leaves you with the least amount of bits. So you still need to convert it to an 8-bit string.

The other thing is, that you can just get the first 8 digits from your binary and trim your input as you go, like in the following example.

function stringToBinary(input) {
var characters = input.split('');

return characters.map(function(char) {
const binary = char.charCodeAt(0).toString(2)
const pad = Math.max(8 - binary.length, 0);
// Just to make sure it is 8 bits long.
return '0'.repeat(pad) + binary;
}).join('');
}

function binaryToString(input) {
let bytesLeft = input;
let result = '';

// Check if we have some bytes left
while (bytesLeft.length) {
// Get the first digits
const byte = bytesLeft.substr(0, 8);
bytesLeft = bytesLeft.substr(8);

result += String.fromCharCode(parseInt(byte, 2));
}

return result;
}

const binary = stringToBinary('test');
console.log({
binary,
text: binaryToString(binary),
});

Fastest way to convert an int into a binary code string in PHP

Benchmarked the following five functions:

// For a baseline, returns unpadded binary
function decBinPlain(int $x) {
return decbin($x);
}

// Alas fancier than necessary:
function decBinDig(int $x) {
return substr(decbin(pow(2, 8) + $x), 1);
}

// OP's initial test
function getBinary(int $x) {
return str_pad(base_convert($x, 10, 2), 8, '0', STR_PAD_LEFT);
}

// OP's function using decbin()
function getDecBin(int $x) {
return str_pad(decbin($x), 8, '0', STR_PAD_LEFT);
}

// TimBrownlaw's method
function intToBin(int $x) {
return sprintf( "%08d", decbin($x));
}

At 500,000 iterations each, run as 10 x (50,000 @ 5), here are the stats:

[average] => [
[decBinPlain] => 0.0912
[getDecBin] => 0.1355
[getBinary] => 0.1444
[intToBin] => 0.1493
[decBinDig] => 0.1687
]
[relative] => [
[decBinPlain] => 100
[getDecBin] => 148.57
[getBinary] => 158.33
[intToBin] => 163.71
[decBinDig] => 184.98
]
[ops_per_sec] => [
[decBinPlain] => 548355
[getDecBin] => 369077
[getBinary] => 346330
[intToBin] => 334963
[decBinDig] => 296443
]

The positions are consistent. OP's function, changed to use decbin in place of base_convert, is the fastest function that returns the complete result, by a very thin margin. I'd opt for decbin simply because the meaning is crystal clear. For adding in the left-padding, str_pad is less complex than sprintf. Running PHP 7.4.4 on W10 & i5-8250U, total runtime 7.11 sec.

For a baseline, calling an empty dummy function averages 0.0542 sec. Then: If you need to run this enough times to worry about minute per-op performance gains, it's more economical to have the code inline to avoid the function call. Here, the overhead from the function call is greater than the difference between the slowest and the fastest options above!

For future reference. If you're bench-marking several options, I'd recommend testing them over a single script call and over several consecutive loops of each function. That'll help even out any "lag noise" from background programs, CPU throttling (power to max if on battery!!) etc. Then, call it a couple of times and see that the numbers are stable. You'll want to do much more than 1000 iterations to get reliable numbers. Try e.g. 10K upwards for more complex functions, and 100K upwards for simpler functions. Burn it enough if you want to prove it!

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/

C++ string to binary code / binary code to string

Are you looking for this ?

  string myString = "Hello World";
std::string binary_outputInformations;
for (std::size_t i = 0; i < myString.size(); ++i)
{
bitset<8> b(myString.c_str()[i]);
binary_outputInformations+= b.to_string();
}

std::cout<<binary_outputInformations;

Output :

0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100

How to convert string to binary representation in game maker?

Tip: search for GML or other language term, these questions answered many times. Also please check your tag as it is the IDE tag, not language tag.

Im not familiar with GML myself, but a quick search showed this:

At least semi-official method for exactly this: http://www.gmlscripts.com/script/bytes_to_bin

/// bytes_to_bin(str)
//
// Returns a string of binary digits, 1 bit each.
//
// str raw bytes, 8 bits each, string
//
/// GMLscripts.com/license
{
var str, bin, p, byte;
str = argument0;
bin = "";
p = string_length(str);
repeat (p) {
byte = ord(string_char_at(str,p));
repeat (8) {
if (byte & 1) bin = "1" + bin else bin = "0" + bin;
byte = byte >> 1;
}
p -= 1;
}
return bin;
}

GML forum (has several examples) https://www.reddit.com/r/gamemaker/comments/4opzhu/how_could_i_convert_a_string_to_binary/

///string_to_binary(string)
var str = argument0;
var output = "";
for(var i = 0; i < string_length(str); i++){
if(string_char_at(str, i + 1) == "0"){
output += "0";
}
else{
output += "1";
}
}
return real(output);


And other language examples:

C++ Fastest way to Convert String to Binary?

#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
string myString = "Hello World";
for (std::size_t i = 0; i < myString.size(); ++i)
{
cout << bitset<8>(myString.c_str()[i]) << endl;
}
}

Java: Convert A String (like testing123) To Binary In Java

  String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);

JS: How to convert text to binary code in JavaScript?

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) + " ";
}
}


Related Topics



Leave a reply



Submit