Javascript string to binary string

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

The fastest possible UCS2 string to character code array and vice-versa javascript converter library there is

License

anonyco/fastest-string-to-binary-to-string-js

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Html check which button is clicked

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A super lightweight javascript utility library for working with high unicode characters

Simply insert the following line of code into your head before any other scripts.

script src pl-s">https://dl.dropboxusercontent.com/s/ll11ftru2az384q/string16.min.js?dl=0">script>

Or, you can super speed up you page by adding the defer=»» attribute to all of your scripts like so. The defer=»» attribute keeps the scripts executing in the same order, but makes the assumtion your script will not call document.write , allowing the browser the parse the whole page before executing the scripts.

> html>head> script src pl-s">https://dl.dropboxusercontent.com/s/ll11ftru2az384q/string16.min.js?dl=0" defer="">script> script src pl-s">/path/to/other/scripts.js" defer="">script> title>Example Domaintitle> head>body> h1>Example Domainh1> body>html>

A common error that might arise (in the console you can get to by pressing Ctrl+Shift+I) from putting the defer=»» attribute into all of your scripts is Uncaught ReferenceError: string16 is not defined . This error is likely caused by one of three things:

script defer=""> var str = "Hello World!"; // . (rest of your javascript code) script>

1.1. The first solution to this is to take that javascirpt code and put it into a separate file. This will work because the defer=»» attribute has no effect on inline javascript code. 1.2 The second option is to wrap your whole script in an event listener function that delays the execution until after the page has loaded like so.

script defer=""> addEventListener("load", function() var str = "Hello World!"; // . (rest of your javascript code) >, once:1>); script>
  1. You did not put defer=»» into all of your scripts. Double check to make sure all your scripts have the defer=»» attribute
  2. You did not put this string16.js script at the top. Make sure string16.js is at the top, before all other scripts.

String16js adds a global window.string16 object for all your strings to use. See the following chart below for what each of theese methods does and an example of how to use it.

document.body.insertAdjacentHTML("beforeend", '
' + string16.arrayToString([65, 32, 55357, 56898, 32, 115, 109, 105, 108, 101, 115]) + '

')

About

The fastest possible UCS2 string to character code array and vice-versa javascript converter library there is

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

JavaScript library to convert any String to Binary Code and vice-versa

s-faisal/str2bin

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

JavaScript library / CLI commands to convert any String to Binary Code and vice-versa.

const str2bin = require("str2bin") str2bin.strToBin(string) str2bin.binToStr(binaryCode, delimiter) str2bin.strToBin("hello") ## returns "01101000 01100101 01101100 01101100 01101111" str2bin.binToStr("01101000 01100101 01101100 01101100 01101111") ## returns "hello" str2bin.binToStr("01101000-01100101-01101100-01101100-01101111", "-") ## returns "hello" 

Install the package globally

npm i -g str2bin ##using NPM OR yarn global add str2bin ##using yarn
## str2bin -s "string_that_needs_to_be_converted" str2bin -s "hello" ## returns "01101000 01100101 01101100 01101100 01101111" ## str2bin -b "binary_string_that_needs_to_be_converted" str2bin -b "01101000 01100101 01101100 01101100 01101111" ## returns 'hello' ## str2bin -b "binary_string_that_needs_to_be_converted" -d "delimiter" str2bin -b "01101000-01100101-01101100-01101100-01101111" -d "-" ## returns "hello" 

About

JavaScript library to convert any String to Binary Code and vice-versa

Источник

How to convert a binary string into a readable string and vice versa with Javascript

Carlos Delgado

Learn how to convert a binary string into a human readable value or a human readable value in a binary string with Javascript.

How to convert a binary string into a readable string and vice versa with Javascript

A binary code is a representation of a text, computer processor instructions, or other data using a two symbol system, often the binary number system is 0 and 1. The binary code assigns a pattern of binary digits (bits) to each character, instruction, etc. For example, a binary string of eight bits can represent any of 256 possible values and can therefore represent a variety of different items. Although with other languages the conversion from a string into its binary notation ain’t so quick and easy with languages like Python or C++ (using bitset ), it still achievable with 3 or 4 lines of code.

In this article you will learn how to convert a string into its binary value and a binary value into a human readable string using Javascript.

Tests

In this article we are going to share with you a couple of methods that convert readable strings into its binary representation or binary strings into readable strings. In order to check if those methods work as expected, we are going to test the method on every object stored in the following variable TestBlock :

Having said that, let’s get started !

Readable string to binary

To convert a human readable string to its binary value, use the following function:

/** * Function that converts a string into its binary representation * * @see https://gist.github.com/eyecatchup/6742657 * @author https://github.com/eyecatchup */ function stringToBinary(str, spaceSeparatedOctets) < function zeroPad(num) < return "00000000".slice(String(num).length) + num; >return str.replace(/[\s\S]/g, function(str) < str = zeroPad(str.charCodeAt().toString(2)); return !1 == spaceSeparatedOctets ? str : str + " " >); >;

And you can use it easily:

// "01001000 01100101 01101100 01101100 01101111 00100000 01000010 01101001 01101110 01100001 01110010 01111001 00100000 01010111 01101111 01110010 01101100 01100100" stringToBinary("Hello Binary World"); 

But how does this code works ? The providen string The charCodeAt method returns the Unicode of the first character in a string. The toString() method parses its first argument, and attempts to return a string representation in the specified radix (base). For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), a through f are used.

If you provide the second parameters ( spaceSeparatedOctets ) to 0, then the string won’t be «pretty printed» (the octets won’t be separated). The test for the stringToBinary method is the following (note that the stringToBinary method adds an empty character at the end of the returned string therefore is recommendable to use the trim method to remove it):

var testsSuccesfullyExecuted = 0; var testErrors = []; TestBlock.forEach(function(item , index)< var processedBinaryString = item.binary; // Removes the spaces from the binary string processedBinaryString = processedBinaryString.replace(/\s+/g, ''); // Pretty (correct) print binary (add a space every 8 characters) processedBinaryString = processedBinaryString.match(/./g).join(" "); // Remove spaces at the end of the stringToBinary generated string if(stringToBinary(item.text).trim() == processedBinaryString) < console.log("Test $passes"); testsSuccesfullyExecuted++; >else < testErrors.push(index); >>); if(testsSuccesfullyExecuted == TestBlock.length)< console.log("Test suite succesfully executed with no errors"); >else

Providing the following output in the console:

Test $ passes Test $ passes Test $ passes Test $ passes Test $ passes Test suite succesfully executed with no errors

With a standard benchmark executed in a personal computer with the following specifications:

  • Windows 10 Pro 64-bit (10.0, Build 14393) — Chrome Version 56.0.2924.87 (64-bit)
  • Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz (8 CPUs), ~3.6GHz
  • 8192MB RAM

The function stringToBinary needed 1322.53 milliseconds to execute the test 10K times with and average execution per task of 0.13194000000025843 milliseconds.

Binary to readable string

To convert a binary string into a readable string, you can use any of the 2 following methods binaryToString or binaryAgent :

Option 1

This function removes all the empty spaces of the string and will split it into blocks of 8 characters that will be joined into a single string. Then the String.fromCharCode will do the trick for you:

function binaryToString(str) < // Removes the spaces from the binary string str = str.replace(/\s+/g, ''); // Pretty (correct) print binary (add a space every 8 characters) str = str.match(/./g).join(" "); var newBinary = str.split(" "); var binaryCode = []; for (i = 0; i < newBinary.length; i++) < binaryCode.push(String.fromCharCode(parseInt(newBinary[i], 2))); >return binaryCode.join(""); >
// Both of them return: "Hello Binary World" binaryToString("0100100001100101011011000110110001101111001000000100001001101001011011100110000101110010011110010010000001010111011011110111001001101100011001000010000000100001"); binaryToString("01001000 01100101 01101100 01101100 01101111 00100000 01000010 01101001 01101110 01100001 01110010 01111001 00100000 01010111 01101111 01110010 01101100 01100100 00100000 00100001");

The test code for binaryToString is the following:

var testsSuccesfullyExecuted = 0; var testErrors = []; TestBlock.forEach(function(item , index) < if(binaryToString(item.binary) == item.text)< console.log("Test $passes"); testsSuccesfullyExecuted++; >else < testErrors.push(index); >>); if(testsSuccesfullyExecuted == TestBlock.length)< console.log("Test suite succesfully executed with no errors"); >else

The following test will output the following content in the console:

Test $ passes Test $ passes Test $ passes Test $ passes Test $ passes Test suite succesfully executed with no errors

Option 2

In the same way the first function does, all the empty spaces will be removed and the string will be divided into blocks of 8 characters to be finally joined.

function binaryAgent(str) < // Removes the spaces from the binary string str = str.replace(/\s+/g, ''); // Pretty (correct) print binary (add a space every 8 characters) str = str.match(/./g).join(" "); return str.split(" ").map(function (elem) < return String.fromCharCode(parseInt(elem, 2)); >).join(""); >
// Both of them return: "Hello Binary World" binaryAgent("0100100001100101011011000110110001101111001000000100001001101001011011100110000101110010011110010010000001010111011011110111001001101100011001000010000000100001"); binaryAgent("01001000 01100101 01101100 01101100 01101111 00100000 01000010 01101001 01101110 01100001 01110010 01111001 00100000 01010111 01101111 01110010 01101100 01100100 00100000 00100001");

The test code for binaryAgent is the following:

var testsSuccesfullyExecuted = 0; var testErrors = []; TestBlock.forEach(function(item , index) < if(binaryAgent(item.binary) == item.text)< console.log("Test $passes"); testsSuccesfullyExecuted++; >else < testErrors.push(index); >>); if(testsSuccesfullyExecuted == TestBlock.length)< console.log("Test suite succesfully executed with no errors"); >else

The following test will output the following content in the console:

Test $ passes Test $ passes Test $ passes Test $ passes Test $ passes Test suite succesfully executed with no errors

Benchmark

The result of a standard benchmark (executed 10K times) with a personal computer with the following specifications:

  • Windows 10 Pro 64-bit (10.0, Build 14393) — Chrome Version 56.0.2924.87 (64-bit)
  • Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz (8 CPUs), ~3.6GHz
  • 8192MB RAM

has generated the following result:

Method Total time (MS) Average time (MS) / Task
binaryToString (Option 1) 1068.54 0.10662899999999208
binaryAgent (Option 2) 1304.80 0.13019300000001968

As you can see the first method is slightly faster than the second.

Источник

Оцените статью