Copyright © https://mongoose-os.com

Mongoose OS Forum

frame
ATTENTION! This forum has moved to:

https://community.mongoose-os.com

Do not post any new messages.

Convert Elements of String to number

I receive an BCD encoded String from my I2C RTC (7 bytes long)

I try to use each element of the string as a number to perform a BCD to DEC conversion.

for (let j = 0; j < result.length; j++) {
        let xx = (result[j]); //Error
        //let xx = 12; //works
        print((xx / 0x10 * 0xA) + (xx % 0x10));
    }

Error:
MJS callback error: implicit type conversion is prohibited

How to explicit convert the char value to a number ? Number() is not working.

Thanks
Holger

Comments

  • SergeySergey Dublin, Ireland

    Are you looking for let num = JSON.parse('123'); ?

  • From my RTC (DS 3231) I receive an 7 Byte long string which contains the data for the time.
    This data is BCD encoded, which ,means the first 4 bits and the second 4 bits encode a digit of the time information ( each byte has 2 digits).

    https://en.wikipedia.org/wiki/BCD_(character_encoding)

    In C it is easy to convert. Take each element from the array of char and do some logic operation.

    In Javascript it seems not possible to access each element of the string as a 8 bit integer and perform logical operations.

    I will now use this example to create a C Function and a wrapper in MJS. At the end I want to create a library for the RTC DS3231.

    Regards
    Holger

  • SergeySergey Dublin, Ireland
    edited June 2017

    Ah, you mean you'd like to get an "ascii value" of the characeter, I think something like this might work:

    "\xc4".charCodeAt(0) & 0xf
    

    charCodeAt(n), basically.

    I noticed it is not documented. The reason being it pretends to be standard, but it is not cause mjs strings are not JS unicode strings, they are byte strings (suitable for embedded, as raw data coming from network or devices are byte streams)

    We might rename to at() and document

  • SergeySergey Dublin, Ireland

    Done, 'str'.at() functionality is documented, https://github.com/cesanta/mjs

  • DrBombDrBomb Venezuela

    very nice! Thank you sergey!

  • Thanks.

    This was what I am looking for.

    Holger

  • tripflextripflex Orlando, FL

    Even if you've already parsed JSON that includes an integer, you have to call JSON.parse( someJson.integerKey );

Sign In or Register to comment.