How do I convert a byte array into a string?
如何将一个字节数组转换成字符串?
I have found these functions that do the reverse:
我发现这些函数的作用正好相反:
function string2Bin(s) {
var b = new Array();
var last = s.length;
for (var i = 0; i < last; i++) {
var d = s.charCodeAt(i);
if (d < 128)
b[i] = dec2Bin(d);
else {
var c = s.charAt(i);
alert(c + ' is NOT an ASCII character');
b[i] = -1;
}
}
return b;
}
function dec2Bin(d) {
var b = '';
for (var i = 0; i < 8; i++) {
b = (d%2) + b;
d = Math.floor(d/2);
}
return b;
}
But how do I get the functions working the other way?
但是我怎样才能让函数反过来呢?
Thanks.
谢谢。
Shao
邵
5 个解决方案
#1
56
You need to parse each octet back to number, and use that value to get a character, something like this:
您需要将每个octet解析为数字,并使用该值来获得一个字符,如下所示:
function bin2String(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
result += String.fromCharCode(parseInt(array[i], 2));
}
return result;
}
bin2String(["01100110", "01101111", "01101111"]); // "foo"
// Using your string2Bin function to test:
bin2String(string2Bin("hello world")) === "hello world";
Edit: Yes, your current string2Bin
can be written more shortly:
编辑:是的,您当前的string2Bin可以写得更短一些:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i).toString(2));
}
return result;
}
But by looking at the documentation you linked, I think that the setBytesParameter
method expects that the blob array contains the decimal numbers, not a bit string, so you could write something like this:
但是通过查看您链接的文档,我认为setBytesParameter方法期望blob数组包含十进制数,而不是位串,所以您可以这样写:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i));
}
return result;
}
function bin2String(array) {
return String.fromCharCode.apply(String, array);
}
string2Bin('foo'); // [102, 111, 111]
bin2String(string2Bin('foo')) === 'foo'; // true
#2
23
Simply apply
your byte array to String.fromCharCode
. For example
简单地将字节数组应用到String.fromCharCode中。例如
String.fromCharCode.apply(null, [102, 111, 111])
equals 'foo'.
apply(null, [102, 111, 111]) = 'foo'。
Caveat: works for arrays shorter than 65535. MDN docs here.
警告:对数组的作用小于65535。MDN文档。
#3
7
That string2Bin can be written even more succinctly, and without any loops, to boot!
这个string2Bin可以写得更简洁,而且没有任何循环,可以启动!
function string2Bin ( str ) {
return str.split("").map( function( val ) {
return val.charCodeAt( 0 );
} );
}
#4
3
I think this would be more efficient:
我认为这样更有效:
function toBinString (arr) {
var uarr = new Uint8Array(arr.map(function(x){return parseInt(x,2)}));
var strings = [], chunksize = 0xffff;
// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
for (var i=0; i*chunksize < uarr.length; i++){
strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize)));
}
return strings.join('');
}
#5
1
Even if I'm a bit late, I thought it would be interesting for future users to share some one-liners implementations I did using ES6.
即使我有点晚了,我认为未来的用户也会有兴趣分享一些我使用ES6实现的单行实现。
One thing that I consider important depending on your environment or/and what you will do with with the data is to preserve the full byte value. For example, (5).toString(2)
will give you 101
, but the complete binary conversion is in reality 00000101
, and that's why you might need to create a leftPad
implementation to fill the string byte with leading zeros. But you may not need it at all, like other answers demonstrated.
根据您的环境或/您将如何处理数据,我认为重要的一点是保存完整的字节值。例如,(5). tostring(2)将给您101,但是完整的二进制转换实际上是00000101,这就是为什么您可能需要创建一个leftPad实现来填充带前导零的字符串字节。但你可能根本不需要它,就像其他的答案一样。
If you run the below code snippet, you'll see the first output being the conversion of the abc
string to a byte array and right after that the re-transformation of said array to it's corresponding string.
如果您运行下面的代码片段,您将看到第一个输出是将abc字符串转换为字节数组,然后将该数组的重新转换为相应的字符串。
// For each byte in our array, retrieve the char code value of the binary value
const binArrayToString = array => array.map(byte => String.fromCharCode(parseInt(byte, 2))).join('')
// Basic left pad implementation to ensure string is on 8 bits
const leftPad = str => str.length < 8 ? (Array(8).join('0') + str).slice(-8) : str
// For each char of the string, get the int code and convert it to binary. Ensure 8 bits.
const stringToBinArray = str => str.split('').map(c => leftPad(c.charCodeAt().toString(2)))
const array = stringToBinArray('abc')
console.log(array)
console.log(binArrayToString(array))
#1
56
You need to parse each octet back to number, and use that value to get a character, something like this:
您需要将每个octet解析为数字,并使用该值来获得一个字符,如下所示:
function bin2String(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
result += String.fromCharCode(parseInt(array[i], 2));
}
return result;
}
bin2String(["01100110", "01101111", "01101111"]); // "foo"
// Using your string2Bin function to test:
bin2String(string2Bin("hello world")) === "hello world";
Edit: Yes, your current string2Bin
can be written more shortly:
编辑:是的,您当前的string2Bin可以写得更短一些:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i).toString(2));
}
return result;
}
But by looking at the documentation you linked, I think that the setBytesParameter
method expects that the blob array contains the decimal numbers, not a bit string, so you could write something like this:
但是通过查看您链接的文档,我认为setBytesParameter方法期望blob数组包含十进制数,而不是位串,所以您可以这样写:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i));
}
return result;
}
function bin2String(array) {
return String.fromCharCode.apply(String, array);
}
string2Bin('foo'); // [102, 111, 111]
bin2String(string2Bin('foo')) === 'foo'; // true
#2
23
Simply apply
your byte array to String.fromCharCode
. For example
简单地将字节数组应用到String.fromCharCode中。例如
String.fromCharCode.apply(null, [102, 111, 111])
equals 'foo'.
apply(null, [102, 111, 111]) = 'foo'。
Caveat: works for arrays shorter than 65535. MDN docs here.
警告:对数组的作用小于65535。MDN文档。
#3
7
That string2Bin can be written even more succinctly, and without any loops, to boot!
这个string2Bin可以写得更简洁,而且没有任何循环,可以启动!
function string2Bin ( str ) {
return str.split("").map( function( val ) {
return val.charCodeAt( 0 );
} );
}
#4
3
I think this would be more efficient:
我认为这样更有效:
function toBinString (arr) {
var uarr = new Uint8Array(arr.map(function(x){return parseInt(x,2)}));
var strings = [], chunksize = 0xffff;
// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
for (var i=0; i*chunksize < uarr.length; i++){
strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize)));
}
return strings.join('');
}
#5
1
Even if I'm a bit late, I thought it would be interesting for future users to share some one-liners implementations I did using ES6.
即使我有点晚了,我认为未来的用户也会有兴趣分享一些我使用ES6实现的单行实现。
One thing that I consider important depending on your environment or/and what you will do with with the data is to preserve the full byte value. For example, (5).toString(2)
will give you 101
, but the complete binary conversion is in reality 00000101
, and that's why you might need to create a leftPad
implementation to fill the string byte with leading zeros. But you may not need it at all, like other answers demonstrated.
根据您的环境或/您将如何处理数据,我认为重要的一点是保存完整的字节值。例如,(5). tostring(2)将给您101,但是完整的二进制转换实际上是00000101,这就是为什么您可能需要创建一个leftPad实现来填充带前导零的字符串字节。但你可能根本不需要它,就像其他的答案一样。
If you run the below code snippet, you'll see the first output being the conversion of the abc
string to a byte array and right after that the re-transformation of said array to it's corresponding string.
如果您运行下面的代码片段,您将看到第一个输出是将abc字符串转换为字节数组,然后将该数组的重新转换为相应的字符串。
// For each byte in our array, retrieve the char code value of the binary value
const binArrayToString = array => array.map(byte => String.fromCharCode(parseInt(byte, 2))).join('')
// Basic left pad implementation to ensure string is on 8 bits
const leftPad = str => str.length < 8 ? (Array(8).join('0') + str).slice(-8) : str
// For each char of the string, get the int code and convert it to binary. Ensure 8 bits.
const stringToBinArray = str => str.split('').map(c => leftPad(c.charCodeAt().toString(2)))
const array = stringToBinArray('abc')
console.log(array)
console.log(binArrayToString(array))