简体   繁体   English

如何将字符串转换为 ECS/P Hex

[英]How to convert string to ECS/P Hex

I'm using jquery / javascript to print raw data to a network label printer.我正在使用 jquery/javascript 将原始数据打印到网络标签打印机。 In order to do that the strings will need to be converted to hexadecimal.为此,需要将字符串转换为十六进制。 with a \\x preceding each character.每个字符前都有一个\\x

SO if I wanted to print a label with " I love stackoverflow " the string would need to be converted to \\x49\\x20\\x6C\\x6F\\x76\\x65\\x20\\x73\\x74\\x61\\x63\\x6B\\x6F\\x76\\x65\\x72\\x66\\x6C\\x6F\\x77 .因此,如果我想打印带有“ I love stackoverflow ”的标签,则需要将字符串转换为\\x49\\x20\\x6C\\x6F\\x76\\x65\\x20\\x73\\x74\\x61\\x63\\x6B\\x6F\\x76\\x65\\x72\\x66\\x6C\\x6F\\x77

I have searched around and I can't find anything on this.我已经四处搜索,但找不到任何关于此的信息。 Any ideas on how this can be achieved?关于如何实现这一目标的任何想法?

I could create a library of variables for each character var A = '/x41;我可以为每个字符创建一个变量库var A = '/x41; and then run the string through a 'checker' that goes through the entire sting, but I feel like I am missing a simpler solution.然后通过贯穿整个字符串的“检查器”运行字符串,但我觉得我缺少一个更简单的解决方案。

You can simply do it this way:你可以简单地这样做:

  • [...str]: convert the string to an array of chars [...str]:将字符串转换为字符数组
  • .map(): apply a function on each char .map():对每个字符应用一个函数
  • convert a char to integer --> to hex number将字符转换为整数 --> 转换为十六进制数
  • join the array: get the hex string加入数组:获取十六进制字符串

 function stringtohex(str) { return [...str].map(e => '\\\\x' + Number(e.charCodeAt(0)).toString(16)).join('') } var convertedstr = stringtohex( "I love stackoverflow"); console.log(convertedstr);

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

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