简体   繁体   English

如何从node.js中的JSON将十六进制字符串解析为十六进制数字

[英]How to parse a hex-string to a hex-number from a JSON in node.js

I want to save the addresses for an i2c device into a JSON file, but I have no idea how to parse the strings I get back into the addresses in hex notation. 我想将i2c设备的地址保存到JSON文件中,但是我不知道如何解析以十六进制表示法返回到地址的字符串。

const dev_address = this.parameters['DEVICE_ADDR']; // 0x04

First I tried .parseInt(this.parameters['DEVICE_ADDR'], 16) , then I thought the addresses might be some kind of byte[] and tried multiple things using buffer.from(str) and .toString('hex') without success. 首先,我尝试了.parseInt(this.parameters['DEVICE_ADDR'], 16) ,然后我认为这些地址可能是某种byte[]并使用buffer.from(str).toString('hex')尝试了多种方法没有成功。

How is this done? 怎么做?


Reference 参考

'use strict';

const logger = require('../controller/LogController');
const i2c = require('i2c-bus');

class ArduinoPlug_on {
    constructor(parameters) {
      this.parameters = parameters;
    }

    run(env) {
      logger.debug('try connection', this.parameters);
      const dev_address = this.parameters['DEVICE_ADDR']; // 0x04
      const opt_address = this.parameters['OPTION_ADDR']; // 0x00

      const i2c1 = i2c.openSync(1);
      const bytesWritten = i2c1.i2cWriteSync(dev_address, 2, Buffer.from([opt_address,0x01]));
      if( bytesWritten == 0 ) {
        logger.error("could not write data", err);
      }
      i2c1.closeSync();
    }

    release(env) {
    }
}
module.exports = ArduinoPlug_on;

I think you're looking for something like this: 我认为您正在寻找这样的东西:

 // Convert a string with hex notation to number var somestring = "0xFF"; var n = parseInt(somestring); console.log(n); // 255 // Convert a number to string with hex notation var somenumber = 0xff; var s = somenumber.toString(16); console.log("0x" + s); // 0xff 

Converting from a String containing a hex number to decimal and back: 从包含十六进制数字的字符串转换为十进制然后返回:

 let num = "0xff"; console.log(Number(num)); // to decimal console.log(`0x${Number(num).toString(16)}`); // to hex notation string 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM