Binary Converter

eyecatchup / ascii-binary-converter.js

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// ABC — a generic, native JS (A)scii(B)inary(C)onverter.
// (c) 2013 Stephan Schmitz
// License: MIT, http://eyecatchup.mit-license.org
// URL: https://gist.github.com/eyecatchup/6742657
var ABC =
toAscii : function ( bin )
return bin . replace ( / \s * [ 01 ] < 8 >\s * / g , function ( bin )
return String . fromCharCode ( parseInt ( bin , 2 ) )
> )
> ,
toBinary : function ( str , spaceSeparatedOctets )
return str . replace ( / [ \s \S ] / g , function ( str )
str = ABC . zeroPad ( str . charCodeAt ( ) . toString ( 2 ) ) ;
return ! 1 == spaceSeparatedOctets ? str : str + » «
> )
> ,
zeroPad : function ( num )
return «00000000» . slice ( String ( num ) . length ) + num
>
> ;

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// ABC — a generic, native JS (A)scii(B)inary(C)onverter.
// (c) 2013 Stephan Schmitz
// License: MIT, http://eyecatchup.mit-license.org
// URL: https://gist.github.com/eyecatchup/6742657
var ABC = < toAscii : function ( a ) < return a . replace ( / \s * [ 01 ] < 8 >\s * / g , function ( a ) < return String . fromCharCode ( parseInt ( a , 2 ) ) >) > , toBinary : function ( a , b ) < return a . replace ( / [ \s \S ] / g , function ( a ) < a = ABC . zeroPad ( a . charCodeAt ( ) . toString ( 2 ) ) ; return ! 1 == b ? a : a + " " >) > , zeroPad : function ( a ) < return "00000000" . slice ( String ( a ) . length ) + a >> ;

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

var binary1 = «01100110011001010110010101101100011010010110111001100111001000000110110001110101011000110110101101111001» ,
binary2 = «01100110 01100101 01100101 01101100 01101001 01101110 01100111 00100000 01101100 01110101 01100011 01101011 01111001» ,
binary1Ascii = ABC . toAscii ( binary1 ) ,
binary2Ascii = ABC . toAscii ( binary2 ) ;
console . log ( «Binary 1: » + binary1 ) ;
console . log ( «Binary 1 to ASCII: » + binary1Ascii ) ;
console . log ( «Binary 2: » + binary2 ) ;
console . log ( «Binary 2 to ASCII: » + binary2Ascii ) ;
console . log ( «Ascii to Binary: » + ABC . toBinary ( binary1Ascii ) ) ; // default: space-separated octets
console . log ( «Ascii to Binary /wo spaces: » + ABC . toBinary ( binary1Ascii , 0 ) ) ; // 2nd parameter false to not space-separate octets

Thanks, but this doesn’t work. Try:

and you will get õ , which is not an ASCII character. ASCII encodes 128 specified characters into 7-bit binary integers. I mention because this is the top-ranked google result for this topic.

Ascii code 228 which you will get with Alt + ‘o’
And is part of the ‘extended Ascii codes’ running up to 255 starting with 0 so 8-bit totaling 256 characters the extended Ascii codes were added in 1981.

Источник

How to convert text to binary using javascript

Then you can convert it to Binary value using : HTML: JS: And here’s a fiddle: http://jsfiddle.net/fA24Y/1/ Solution 2: This might be the simplest you can get: Solution 3: traverse the string convert every character to their char code convert the char code to binary push it into an array and add the left 0s return a string separated by space Code: Another way Solution 4: Here’s a pretty generic, native implementation, that I wrote some time ago, and to be used as follows: Source is on Github (gist): https://gist.github.com/eyecatchup/6742657 I want JavaScript to translate text in a textarea into binary code.

How to convert text to binary code in JavaScript?

Text to Binary Code

I want JavaScript to translate text in a textarea into binary code.

For example, if a user types in » TEST » into the textarea, the value » 01010100 01000101 01010011 01010100 » should be returned.

I would like to avoid using a switch statement to assign each character a binary code value (e.g. case «T»: return «01010100 ) or any other similar technique.

Here’s a JSFiddle to show what I mean. Is this possible in native 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) :

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

This might be the simplest you can get:

function text2Binary(string) < return string.split('').map(function (char) < return char.charCodeAt(0).toString(2); >).join(' '); > 
  1. traverse the string
  2. convert every character to their char code
  3. convert the char code to binary
  4. push it into an array and add the left 0s
  5. return a string separated by space
function textToBin(text) < var length = text.length, output = []; for (var i = 0;i < length; i++) < var bin = text[i].charCodeAt().toString(2); output.push(Array(8-bin.length+1).join("0") + bin); >return output.join(" "); > textToBin("!a") => "00100001 01100001" 
function textToBin(text) < return ( Array .from(text) .reduce((acc, char) =>acc.concat(char.charCodeAt().toString(2)), []) .map(bin => '0'.repeat(8 - bin.length) + bin ) .join(' ') ); > 

Here’s a pretty generic, native implementation, that I wrote some time ago,

// ABC - a generic, native JS (A)scii(B)inary(C)onverter. // (c) 2013 Stephan Schmitz // License: MIT, http://eyecatchup.mit-license.org // URL: https://gist.github.com/eyecatchup/6742657 var ABC = < toAscii: function(bin) < return bin.replace(/\s*[01]\s*/g, function(bin) < return String.fromCharCode(parseInt(bin, 2)) >) >, toBinary: function(str, spaceSeparatedOctets) < return str.replace(/[\s\S]/g, function(str) < str = ABC.zeroPad(str.charCodeAt().toString(2)); return !1 == spaceSeparatedOctets ? str : str + " " >) >, zeroPad: function(num) < return "00000000".slice(String(num).length) + num >>; 

and to be used as follows:

var binary1 = "01100110011001010110010101101100011010010110111001100111001000000110110001110101011000110110101101111001", binary2 = "01100110 01100101 01100101 01101100 01101001 01101110 01100111 00100000 01101100 01110101 01100011 01101011 01111001", binary1Ascii = ABC.toAscii(binary1), binary2Ascii = ABC.toAscii(binary2); console.log("Binary 1: " + binary1); console.log("Binary 1 to ASCII: " + binary1Ascii); console.log("Binary 2: " + binary2); console.log("Binary 2 to ASCII: " + binary2Ascii); console.log("Ascii to Binary: " + ABC.toBinary(binary1Ascii)); // default: space-separated octets console.log("Ascii to Binary /wo spaces: " + ABC.toBinary(binary1Ascii, 0)); // 2nd parameter false to not space-separate octets 

Source is on Github (gist): https://gist.github.com/eyecatchup/6742657

Hope it helps. Feel free to use for whatever you want (well, at least for whatever MIT permits) .

How to convert text to binary code in JavaScript?, I want JavaScript to translate text in a textarea into binary code. For example, if a user types in «TEST» into the textarea, the value «01010100 01000101 01010011 01010100» should be returned. I would like to avoid using a switch statement to assign each character a binary code value (e.g. case «T»: return «01010100) or any other similar Code samplefunction convert()

How to convert text to binary using javascript

I want to make a text to binary converter. For example if someone types in ‘Hello’ it would return 0100100001100101011011000110110001101111 How can I do this? I have tried this but something is wrong:

         

Any help will be greatly appreciated. Thanks, Omar.

function convertBinary() < var output = document.getElementById("outputBinary"); var input = document.getElementById("inputBinary").value; output.value = ""; for (i=0; i < input.length; i++) while(e!=0); while(s.length <8)output.value+=s; > > 

How to convert text to binary using javascript, I want to make a text to binary converter. For example if someone types in ‘Hello’ it would return 0100100001100101011011000110110001101111 How can I do this? I have

Converting a string into binary and back

I got an assignment to convert a given string into binary and back to a string again.

function stringToBinary(input) < var characters = input.split(''); return characters.map(function(char) < return char.charCodeAt(0).toString(2) >).join(''); >alert(stringToBinary('test'))

However I cannot get my head around how to break the resulting string into their bytes. I tried this so far:

function binaryToString(input) < var bits = input.split(''); var byte = ''; return bits.map(function(bit) < byte = byte + bit; if (byte.length == 8) < var char = byte; // how can I convert this to a character again? byte = ''; return char; >return ''; >).join(''); >alert(binaryToString('1110100110010111100111110100'));

How can I convert a byte into a character again? And it also feels a bit odd. Is there a better, faster way to collect those bytes

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), >);

First of all, you need to take the same length of the converted string as input for the conversion back to a string, by taking String#padStart with a length of 8 and a filling character of zero.

function stringToBinary(input) < var characters = input.split(''); return characters .map(function(char) < return char.charCodeAt(0).toString(2).padStart(8, 0) >) .join(' '); // show with space for each byte // watch leading zero, which is missed in the former code >console.log(stringToBinary('test'))

The you need to take this string and split it into a length of eight characters and convert it back.

function binaryToString(input) < return input .match(/./g) // take 8 characters .map(function(byte) < return String.fromCharCode(parseInt(byte, 2)); >) .join(''); >console.log(binaryToString('01110100011001010111001101110100'));

While you are asking for a faster way, you could spread the splitted converted bytes to the fromCharCode function.

function binaryToString(input) < return String .fromCharCode(. input .match(/./g) .map(byte => parseInt(byte, 2)) ); >console.log(binaryToString('01110100011001010111001101110100'));

I just worked on exact project right now, here are the functions to convert from text to binary and from binary to text:

function binaryToTexttConverter(str) < let wordArray = []; let message = str.split(" ").map((stack) =>< let numberArray = parseInt(stack, 2); let letters = String.fromCharCode(numberArray); wordArray.push(letters); >); let output = wordArray.join(""); console.log(output); return output; > // binaryToTexttConverter("test binary"); ***************************************************************** function textToBinaryConverter(str) < let xterCodesArray = []; let splitted = str.split(""); for (i = 0; i < splitted.length; i++) < let xterCodes = splitted[i].charCodeAt(splitted[i]); xterCodesArray.push(xterCodes.toString(2)); >console.log(xterCodesArray.join(" ")); return xterCodesArray.join(" "); > // textToBinaryConverter("test string"); 

Javascript — Converting a string into binary and back, 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.

Источник

Как преобразовать строки в бинарный код в JS?

есть ли какие то встроенные (можно и модуль импортировать) способы перевода текста в UTF-8 (или 16), а его в двоичное представление? Естественно, что онлайн перевод невозможен, а писать функцию по переводу не хочу, ибо потребуется для каждого символа копировать его UTF версию, а для каждого UTF символа его бин версию

Простой 3 комментария

Rsa97

Строка и так хранится в двоичном представлении, по другому компьютер не умеет. Или вы что-то другое имеете в виду?

Rsa97, очень логично, но я про то, как сохранить в переменной её текст в двоичном коде. Вот строка «А» в UTF-8 в десятичном и шестандцатеричном представлении — «208 144» и «D090». Как преобразовать ее в UTF-8/16, а затем в двоичный код методами JS? То есть вот строка «Хай», и после преобразования должно возвращаться «D0A5 D0B0 D0B9» в шестнадцатеричном представлении.

code = "й".charCodeAt(0) //1081 или 0x0439
byteCode1 = code >> 6 | 0b11000000; byteCode2 = code & 0b00111111 | 0b10000000;

Остаётся всё это склеить в одну функцию. В императивном стиле, конечно же, чтобы было понятно, что происходит:

function StringToBin(s) < let arr = s.split(''); //разбиваем строку на символы arr.forEach((symbol, index) =>< //кодируем каждый символ let code = symbol.charCodeAt(0); let byteCode1 = code >> 6 | 0b11000000; let byteCode2 = code & 0b00111111 | 0b10000000; arr[index] = (code < 128 ? code.toString(16) : byteCode1.toString(16) + byteCode2.toString(16)).toUpperCase(); >); return arr.join(' '); //возвращаем кодированную строку > console.log(StringToBin("Хай")); //D0A5 D0B0 D0B9

Но повторюсь, это упрощённый алгоритм, когда октетов не более двух. Если нужен универсальный вариант, то вам нужно слегка улучшить эту функцию. Проблем не должно возникнуть, ведь я рассказал, как и что нужно делать.

Rsa97

'Строка'.split('').map(c => c.codePointAt(0).toString(16)).join(' '); // "421 442 440 43e 43a 430"
Array.from(new TextEncoder().encode('строка')).map(c => c.toString(16)).join(' '); // "d1 81 d1 82 d1 80 d0 be d0 ba d0 b0"

Источник

Читайте также:  Open sans semibold css
Оцените статью