格式和十六进制的Javascript编码器问题

时间:2019-09-25 15:07:45

标签: javascript json hex encode lorawan

我正在使用JavaScript为LoRaWAN编码器。我收到以下数据字段:

{“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547}

我需要用十六进制消息编码,我的代码是:

var header = byteToHex(object.header);
var sunrise =byteToHex(object.sunrise);
var sunset = byteToHex(object.sunset);
var la = parseInt(object.lat100,10);
var lat = swap16(la);
var lo = parseInt(object.long100,10);
var lon = swap16(lo);
var message={};
if (object.header === 6){
    message = (lon)|(lat<<8);
    bytes = message;
}
return hexToBytes(bytes.toString(16));

函数byteToHex / swap16定义为:

function byteToHex(byte) {
    var unsignedByte = byte & 0xff;
    if (unsignedByte < 16) {
        return ‘0’ + unsignedByte.toString(16);
    } else {
        return unsignedByte.toString(16);
    }
}

function swap16(val) {
    return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF);
}

使用返回消息= lon测试它会以十六进制形式生成B3 09。 用message = lon测试它| lat << 8返回96 BB 09,但我要查找的结果是96 19 B3 09(由lon + lat组成)。

有什么提示吗?我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我使用以下代码解决了这个问题:

    var long = object.long;
    var lat = object.lat;
    lat = parseInt(lat*100,10);
    var la = swap16(lat);
    la = la.toString(16);
    long = parseInt(long*100,10);
    var lon = swap16(long);
    lon = lon.toString(16);
    var header = object.header;
    var result= la;
    result+= lon;
    result= result.toString(16);
    bytes = hexToBytes(result);
  }
  }
  return bytes;

现在的响应是:

// encoded payload:
96 19 B3 09