Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle C like struct union type on Nodejs Buffer?

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;
like image 436
Caio Luts Avatar asked Jan 12 '14 04:01

Caio Luts


1 Answers

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)

like image 95
Matt Greer Avatar answered Sep 21 '22 06:09

Matt Greer