7

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;
3
  • The data structure will be 32 bits, and it shows you what each range of bits means, You'd just need to do some bitwise operations to extract each piece in JS. Commented Jan 12, 2014 at 4:39
  • I really don't know how, could you show me an example? Commented Jan 12, 2014 at 4:41
  • Someone has started on a ctypes port for node.js: github.com/rmustacc/node-ctype That will parse most C structures, but it doesn't yet have arbitrary bit-field support, so manual bitwise manipulation like @MattGreer said would still be necessary in this case. Commented Jan 12, 2014 at 5:05

1 Answer 1

9

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer gave me a better understanding of bitwise, and I can continue from now, I'm really glad and I can't thank you enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.