javascript - How can I handle C like struct union type on Nodejs Buffer? - Stack Overflow

I'm trying to parse a buffer on Nodejs that makes use of a struct union type, how can I handle thi

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 pletely 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;

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 pletely 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;
Share Improve this question edited Jan 12, 2014 at 4:37 Caio Luts asked Jan 12, 2014 at 4:31 Caio LutsCaio Luts 3672 silver badges15 bronze badges 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. – Matt Greer Commented Jan 12, 2014 at 4:39
  • I really don't know how, could you show me an example? – Caio Luts Commented Jan 12, 2014 at 4:41
  • Someone has started on a ctypes port for node.js: github./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. – David-SkyMesh Commented Jan 12, 2014 at 5:05
Add a ment  | 

1 Answer 1

Reset to default 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)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745035839a4607513.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信