0

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;
kappes
  • 1
  • 1
  • 2
  • “the addresses in hex notation” are just numbers, once you have parsed the string `"0x04"` to a number (ie, `4`) there is no further magic to do at least from a js standpoint. – James Sep 05 '18 at 12:22
  • Possible duplicate of [How to convert decimal to hex in JavaScript?](https://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript) – connexo Sep 05 '18 at 12:31

2 Answers2

3

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
connexo
  • 53,704
  • 14
  • 91
  • 128
1

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
lviggiani
  • 5,824
  • 12
  • 56
  • 89