kappes
kappes

Reputation: 1

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.

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.

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;

Upvotes: 0

Views: 7177

Answers (2)

connexo
connexo

Reputation: 56803

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

Upvotes: 3

lviggiani
lviggiani

Reputation: 6086

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

Upvotes: 1

Related Questions