在 javascript(不使用节点)上,当使用库( https://github.com/paroga/cbor-js)和在线使用 CBOR(https://cbor.me/ )进行 CBOR 编码时,我面临不同的结果。请注意,即使使用更新的 CBOR 库,结果也是相同的。
例如设置一个对象,例如:
const initial = { 1: "John", "-2": 456 };
使用 CBOR 在线编码给出:a201644a6f686e622d321901c8。详情如下:
A2 # map(2)
01 # unsigned(1)
64 # text(4)
4A6F686E # "John"
62 # text(2)
2D32 # "-2"
19 01C8 # unsigned(456)
现在在 javascript 上使用 CBOR 库进行编码会产生不同的结果:a26131644a6f686e622d321901c8
在在线 CBOR 上解码以上十六进制时,我得到:{“1”:“John”,“-2”:456}。结果几乎与常量 'initial' 相同,只是键 1 现在带有引号 (")。
CBOR online 将我的十六进制值重新格式化为更“可读”的视图:
A2 # map(2)
61 # text(1)
31 # "1"
64 # text(4)
4A6F686E # "John"
62 # text(2)
2D32 # "-2"
19 01C8 # unsigned(456)
请参阅下面我的 Javascript 代码:
//convert an array of bytes (as 8 bits) to string of Hex. ensure that Hex value are not return with 1 digit but 2 digits. ie '01' instead of '1'
function toHexString(byteArray) {
var s = '';
byteArray.forEach(function(byte) {
s += ('0' + (byte & 0xFF).toString(16)).slice(-2);
});
return s;
}
const initial = { 1: "John", "-2": 456 };
var encoded = CBOR.encode(initial);
var encodedHex = toHexString(Array.from(new Uint8Array(encoded)));
console.log ( encodedHex );
我可以手动替换特定的十六进制值,例如:
'61 31 64' 替换为 '01 64'
但不要想这样做,因为列表对于涵盖所有可能的选项可能很重要。
是否有人有解决方法,因为我需要我的结果是 'a201644a6f686e622d321901c8' 而不是 'a26131644a6f686e622d321901c8' ?