简体   繁体   English

如何在 7 位上将字符串转换为二进制? (JavaScript)

[英]How to convert string to binary on 7 bits? (JavaScript)

I need to convert a string to binary specifically on 7 bits.我需要专门在 7 位上将字符串转换为二进制。

'%'.charCodeAt().toString(2)

The above code return 100101, I think it convert on 8 bits.上面的代码返回 100101,我认为它转换为 8 位。 (so this link How to convert text to binary code in JavaScript? is not helping me). (所以这个链接How to convert text to binary code in JavaScript?对我没有帮助)。

% is equal to 0100101 in binary on 7 bits. %等于 0100101 的 7 位二进制数。

The only links I found on SO are about Java.我在 SO 上找到的唯一链接是关于 Java。

You can try this with the help of String.prototype.patStart()您可以在String.prototype.patStart()的帮助下尝试此操作

 const sevenBitBinary = (char) => char.charCodeAt().toString(2).padStart(7, '0'); console.log(sevenBitBinary('%'));

You can add 0s add the beginning with .padStart .您可以添加 0 以.padStart开头。

I think it can help you我认为它可以帮助你

 function get7BitsBinaryString(number) { var result = ''; var bits = [64, 32, 16, 8, 4, 2, 1]; bits.forEach(bit => { if ((bit & number) === bit) { result += '1'; } else { result += '0'; } }); return result; } console.log(get7BitsBinaryString('%'.charCodeAt()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM