admin管理员组文章数量:1315970
I got an assignment to convert a given string into binary and back to a string again.
The first part was easy
function stringToBinary(input) {
var characters = input.split('');
return characters.map(function(char) {
return char.charCodeAt(0).toString(2)
}).join('');
}
alert(stringToBinary('test'))
I got an assignment to convert a given string into binary and back to a string again.
The first part was easy
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
Share Improve this question edited Nov 11, 2018 at 10:51 Nina Scholz 387k26 gold badges363 silver badges413 bronze badges asked Nov 11, 2018 at 9:59 ger616c64ger616c64 611 gold badge1 silver badge5 bronze badges 1- Possible duplicate of Converting Binary to text using javascript – Tigger Commented Nov 11, 2018 at 10:04
3 Answers
Reset to default 5There 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(/.{8}/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(/.{8}/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");
本文标签: javascriptConverting a string into binary and backStack Overflow
版权声明:本文标题:javascript - Converting a string into binary and back - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741994647a2409798.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论