I'm trying to parse a buffer on Nodejs that makes use of a struct union type, how can I handle this natively on Nodejs? I'm completely lost.
typedef union
{
unsigned int value;
struct
{
unsigned int seconds :6;
unsigned int minutes :6;
unsigned int hours :5;
unsigned int days :15; // from 01/01/2000
} info;
}__attribute__((__packed__)) datetime;
This union is either a 32bit integer value
, or the info
struct which is those 32 bits separated out into 6, 6, 5 and 15 bit chunks. I've never interopted with something like this in Node, but I suspect in Node it would just be a Number. If that is the case, you can get at the pieces like this:
var value = ...; // the datetime value you got from the C code
var seconds = value & 0x3F; // mask to just get the bottom six bits
var minutes = ((value >> 6) & 0x3F); // shift the bits down by six
// then mask out the bottom six bits
var hours = ((value >> 12) & 0x1F); // shift by 12, grab bottom 5
var days = ((value >> 17) & 0x7FFF); // shift by 17, grab bottom 15
If you're not familiar with bitwise manipulation, this might look like voodoo. In that case, try out a tutorial like this one (it's for C, but it still largely applies)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With