javascript:字符串到字节[] 到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17720394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:21:04  来源:igfitidea点击:

javascript: String to Byte[] to String

javajavascriptstringbytearray

提问by Riahi

I coded my application in java in a first time and I should now coded it in javascript and I have some problems in the handling of string and arraybytes in javascript and recoding methods of conversion in both directions. Here is my java code:

我第一次用 java 编码我的应用程序,我现在应该用 javascript 编码它,我在处理 javascript 中的字符串和数组字节以及重新编码双向转换方法时遇到了一些问题。这是我的Java代码:

    public String VerifyPIN(String PIN, String successCb, String errorCb)   {
        byte[] AID = new byte[] {(byte)0xA0,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x04,(byte)0x10,(byte)0x10,(byte)0x11};
        byte[] tmpPIN = new byte[] {(byte)0x00, (byte)0x20, (byte)0x00, (byte)0x80, (byte)0x08, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00};
        System.arraycopy(PIN.getBytes(), 0, tmpPIN, 5, PIN.getBytes().length);

        byte[] output = exchange(AID, tmpPIN);
        String result = StringUtils.bytesToString(output);

        if ("90 00".equals(result.trim())) {
            //onSuccess()
        } else {
            //onError
        }

        return result.trim();
    }

    public String bytesToString(byte[] bytes) {
        if (bytes != null)
        {
            StringBuffer sb = new StringBuffer();
            for (byte b : bytes) {
                sb.append(String.format("%02x ", b & 0xFF));
            }
            return sb.toString();
        }
        else {
            return "N/A";
        }

    }

So how can I convert these two methods bytesToStringand VerifyPINto javascript.

那么如何将这两种方法bytesToStringVerifyPIN转换为javascript。

thank you in advance

先感谢您

回答by vipulsharma

You can use

您可以使用

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

Good luck

祝你好运

回答by Akram Fares

For the second method, here is the conversion:

对于第二种方法,这里是转换:

function bytesToString(bytes) {
  var result = "";
  for (var i = 0; i < bytes.length; i++) {
    result += String.fromCharCode(parseInt(bytes[i], 2));
  }
  return result;
}