[英]Is there an equivalent for C# Enumerable for converting string to byte array in NodeJs?
我正在將十六進制字符串發送到函數,並使用c#將其作為字節數組返回,但是現在的要求是在NodeJs中執行此操作。
我對此進行了過多搜索,但非解決方案給了我相同的結果
這是我的十六進制字符串的C#代碼
`8001000501335688003300020002000200`
public static byte[] StringToByteArray(string hex)
{
var byteArray = Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x =>Convert.ToByte(hex.Substring(x,2),16))
.ToArray();
return byteArray;
}
我在NodeJs中嘗試了此代碼,但沒有得到相同的結果
function StringToByteArray(hex) {
var rangebytes = range(0, hex.length).filter(x => x % 2 == 0)
var filteredHex = rangebytes.match(x =>
Buffer.from(hex.substring(x, 2), "utf8"));
return filteredHex;
}
function range(start, count) {
return Array.apply(0, Array(count))
.map(function (element, index) {
return index + start;
});
}
這是C#代碼http://prntscr.com/m7xnzg的結果
此函數將十六進制字符串轉換為Node.js中的字節數組:
function hexStringToByteArray(hexStr) { let a = []; for(let c = 0; c < hexStr.length; c += 2) { a.push(parseInt(hexStr.substr(c, 2), 16)); } return a; } console.log("Result: ", hexStringToByteArray("8001000501335688003300020002000200"));
為此,最好使用Buffer API:
Buffer.from('8001000501335688003300020002000200', 'hex')
// <Buffer 80 01 00 05 01 33 56 88 00 33 00 02 00 02 00 02 00>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.