当前位置:Gxlcms > PHP教程 > javascript-json十六进制被转换为字符串

javascript-json十六进制被转换为字符串

时间:2021-07-01 10:21:17 帮助过:53人阅读

var cmd = ["0x02,0x03,0xB4,0xB4,0x00,0x06","0x00,0x02,0x6E,0x00,0x00,0x05","0x01,0x01,0x00,0x78,0x00,0x05","0x03,0x03,0x82,0x96,0x00,0x05"];
var cmd1=[0x02, 0x03, 0xB4, 0xB4, 0xFF, 0xFF,0x02, 0x03, 0xB4, 0xB4, 0x00, 0x06,0x00, 0x02, 0x6E, 0x00, 0x00, 0x05,0x01, 0x01, 0x00, 0x78, 0x00, 0x05,0x03, 0x03, 0x82, 0x96, 0x00, 0x05];
var test =["0x02,0x03,0xB4,0xB4,0x00,0x06","0x00,0x02,0x6E,0x00,0x00,0x05","0x01,0x01,0x00,0x78,0x00,0x05","0x03,0x03,0x82,0x96,0x00,0x05"];
var cloud = [0x02, 0x03, 0xB4, 0xB4, 0xFF, 0xFF,
    0x02, 0x03, 0xB4, 0xB4, 0x00, 0x06,
    0x00, 0x02, 0x6E, 0x00, 0x00, 0x05,
    0x01, 0x01, 0x00, 0x78, 0x00, 0x05,
    0x03, 0x03, 0x82, 0x96, 0x00, 0x05
];

代码如上

cmd 是通过PHP 转换得到的16进制编码但是JS 取到的时候已经变成了字符串
想实现将cmd 变成跟cmd1 一样的十六进制 截图蓝色部分为想要的效果 红色是数据内容

回复内容:

var cmd = ["0x02,0x03,0xB4,0xB4,0x00,0x06","0x00,0x02,0x6E,0x00,0x00,0x05","0x01,0x01,0x00,0x78,0x00,0x05","0x03,0x03,0x82,0x96,0x00,0x05"];
var cmd1=[0x02, 0x03, 0xB4, 0xB4, 0xFF, 0xFF,0x02, 0x03, 0xB4, 0xB4, 0x00, 0x06,0x00, 0x02, 0x6E, 0x00, 0x00, 0x05,0x01, 0x01, 0x00, 0x78, 0x00, 0x05,0x03, 0x03, 0x82, 0x96, 0x00, 0x05];
var test =["0x02,0x03,0xB4,0xB4,0x00,0x06","0x00,0x02,0x6E,0x00,0x00,0x05","0x01,0x01,0x00,0x78,0x00,0x05","0x03,0x03,0x82,0x96,0x00,0x05"];
var cloud = [0x02, 0x03, 0xB4, 0xB4, 0xFF, 0xFF,
    0x02, 0x03, 0xB4, 0xB4, 0x00, 0x06,
    0x00, 0x02, 0x6E, 0x00, 0x00, 0x05,
    0x01, 0x01, 0x00, 0x78, 0x00, 0x05,
    0x03, 0x03, 0x82, 0x96, 0x00, 0x05
];

代码如上

cmd 是通过PHP 转换得到的16进制编码但是JS 取到的时候已经变成了字符串
想实现将cmd 变成跟cmd1 一样的十六进制 截图蓝色部分为想要的效果 红色是数据内容

cmd.join().split(',').map(function(v) {return parseInt(v,16);});

JSON.stringify()
括号里写变量

cmd.join().split(',').map(function(v) {return parseInt(v);});

var cmd = ["0x02,0x03,0xB4,0xB4,0x00,0x06","0x00,0x02,0x6E,0x00,0x00,0x05","0x01,0x01,0x00,0x78,0x00,0x05","0x03,0x03,0x82,0x96,0x00,0x05"];
var cmd1 = [];
// 转换为整数数组
cmd.forEach(function(d){
    d.split(",").forEach(function(d){
        cmd1.push(parseInt(d));
    })
});

// 打印
输出16进制格式字符串 var output = "var cmd1=["; cmd1.forEach(function(d,i){ var _u = d.toString(16).toUpperCase(); output += "0x"+ (_u.length<2 ? "0"+_u : _u); if(i!=cmd1.length-1) output+=","; }); output += "]"; // 输出字符串:var cmd1=[0x02,0x03,0xB4,0xB4,0x00,0x06,0x00,0x02,0x6E,0x00,0x00,0x05,0x01,0x01,0x00,0x78,0x00,0x05,0x03,0x03,0x82,0x96,0x00,0x05] console.log(output);

人气教程排行