0

Can I allocate n length bit fields in memory?

If this answer is yes, can I make an operation such as addition and multiplication in this field?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • AFAIK nasm only deals with bytes and larger. If you want bit fields you have to shift and mask them by hand. Likewise x86 has no instructions for arithmetic on bitfields - you have to write more instructions to extract and pack them if needed. – Nate Eldredge May 27 '21 at 21:50
  • So, how can I allocate bit field of length n? @NateEldredge – yulaf_ve_abant May 27 '21 at 22:06
  • 2
    On its face, you can't. You'll have to figure out what exactly you mean by that, in terms of bytes. – Nate Eldredge May 27 '21 at 22:07
  • I did not understand why I could not allocate the bit field. Is it possible for me to do something like this ; access any bit in a byte ? @NateEldredge – yulaf_ve_abant May 27 '21 at 22:22
  • 2
    You can allocate the bit field -- just allocate enough bytes to hold it (each byte holds 8 bits). Also, you can pay attention to alignment, mandatory on some architectures, but optional on others. So for example, if your bit field is 24 bits, then maybe allocate a 4 byte integer to hold it; that's rounding up the 24-bit size to 4 bytes. – Erik Eidt May 27 '21 at 22:34
  • Thanks you, @ErikEidt. How do I multiplication the bıt fıelds I've allocate? MUL (NASM) seems to not work in this case. – yulaf_ve_abant May 27 '21 at 22:50
  • 1
    The processor doesn't naturally handle bit fields, so if you have one in memory, you'll need to load bytes into a register and isolate the bit field's bits from the bits that aren't in the bit field. Since we can only load bytes and a few multiples of bytes, there can be extra bits loaded from memory that belong to another bit field or are otherwise undesirable. That's what the others are saying with shift and mask, etc.. In short, to store a bit field, simply round up to a full byte multiple, then in usage, strip off the unwanted bits.. – Erik Eidt May 27 '21 at 23:17
  • 2
    Look at compiler output for a C function that does what you want, with a C struct using a bitfield. e.g. `gcc -O2 -march=native` for example. [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116). That might be a good starting point to optimize from. Note that you almost certainly don't want `mul`, usually just `imul reg, reg` after zero-extending the inputs to 32 or 64-bit, unless you actually want a double-width result split across two registers. – Peter Cordes May 28 '21 at 00:24

0 Answers0