4 ms·
When writing network protocols or de-marshalling binary data it's common to want to know which bits are set in a byte. You might do a & 4 == 4 to test the 3rd
by buzzkills 14y ago
When writing network protocols or de-marshalling binary data it's common to want to know which bits are set in a byte. You might do
a & 4 == 4
to test the 3rd bit is set, how would you do this with 'regular programming'?
- altcognito 14y agoI'm guessing that writing networking protocols and even de-marshaling binary data doesn't fall under "regular programming". The vast majority of programming is business programming and marshalling and de-marshalling data is relatively troublesome (Ruby anyone?). Most of these projects are better off using a library than implementing their own.
- VLM 14y agoI'm sad to say I've seen code where the answer is sprintf hex output into a temp string and some string functions to see if the last single char substring eq and/or neq certain values at the string level correlating with the 3rd bit being set (so ends in hex 2, well that means bit 3 can't be set... ends in hex 4 ding ding ding we have a winner) Only a slight upgrade in readability on a chain of mystifying if/then/else is a case statement with 16 possibilities. Only a slight upgrade on that is "optimizing" for speed by squirting out octal so your lookup stable is half the size of a hex one.
- dspeyer 14y agostruct header __atribute__((packed)) { unsigned int highnibble : 4; unsigned int flag_foo : 1; unsigned int flag_bar : 1; unsigned int flag_baz : 1; unsigned int flag_qux : 1; } if (((header)value).flag_bar) {