Converting bit position to mask value

1

I want to calculate the value of the mask dynamically based on bit position.

For Example: The mask value for the 17th bit in a 32-bit value is 0x00020000 and that of the 18th bit is 0x00040000. So if I know the bit positions like 17, 18 etc., how can this be converted dynamically to mask values in C? Of course left shifting is one method (1<<17 or 1<<18). But I am thinking left shifting may consume too many instructions! Or is left shifting itself the best and efficient method?

c
embedded
asked on Stack Overflow Mar 29, 2015 by Mahesha Padyana • edited Mar 29, 2015 by emlai

2 Answers

6

Basically, it won't consume too many instructions. What you are doing may be fine in one operation. Here is an answer that explains this on SO: Which is faster: x<<1 or x<<10? Basically there is no difference in speed.

Please see this answer on SO too for implementations: How do you set, clear, and toggle a single bit?

answered on Stack Overflow Mar 29, 2015 by Drakes • edited May 23, 2017 by Community
2

In most architectures support a single atomic instruction for logical-shift-left. For example:

  • MIPS: SSL
  • ARM: LSL
  • x86: SHL
  • AVR: LSL

PIC microcontrollers are however a more complex story. Different versions of PIC have different instruction sets, and not all include a logical-shift-left. Low-end (prior to PIC24/sdPIC) PIC instruction sets are not particularly suited to C code generation in any case since they lack direct support for many apparently insignificant C operations.

You should check your target's instruction set and the actual assembler/machine code generated by your compiler - most compilers have support for outputting assembler listings, or you can disassemble the output in your debugger or simulator, or a standalone disassembler.

In the unlikely absence of an logical-shift-left or a compiler optimisation that makes best use of the existing instruction set, you could (at no insignificant memory cost) use a look-up table to at least optimise for time, but in most cases a part with no logical-shift-left is likely to also have very small memory resources, so it is perhaps an impractical solution.

answered on Stack Overflow Mar 29, 2015 by Clifford

User contributions licensed under CC BY-SA 3.0