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
1 Answer
Reset to default 9This 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条)