Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
You are viewing an older revision! See the latest version
Bitmanipulationen Erweitert
Verwendung von Funktionen¶
int setBit(int x, unsigned char position)
{
int mask = 1 << position;
return x | mask;
}
int clearBit(int x, unsigned char position)
{
int mask = 1 << position;
return x & ~mask;
}
int modifyBit(int x, unsigned char position, bool newState)
{
int mask = 1 << position;
int state = int(newState); // relies on true = 1 and false = 0
return (x & ~mask) | (-state & mask);
}
int flipBit(int x, unsigned char position)
{
int mask = 1 << position;
return x ^ mask;
}
bool isBitSet(int x, unsigned char position)
{
x >>= position;
return (x & 1) != 0;
}
Verwendung von Marcros¶
#define BOOL(x) (!(!(x))) #define BitSet(arg,posn) ((arg) | (1L << (posn))) #define BitClr(arg,posn) ((arg) & ~(1L << (posn))) #define BitTst(arg,posn) BOOL((arg) & (1L << (posn))) #define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))
Dies eine allgemeine Lösung für eine ganze Klasse von Problemen. Es ist natürlich möglich und sogar angebracht, jedes Mal, wenn Sie eines dieser Makros benötigen, das Äquivalent eines dieser Makros mit expliziten Maskenwerten neu zu schreiben, aber warum? Denken Sie daran, dass die Makrosubstitution im Präprozessor erfolgt und der generierte Code die Tatsache widerspiegelt, dass die Werte vom Compiler als konstant angesehen werden - dh, es ist genauso effizient, die verallgemeinerten Makros zu verwenden, als das Rad jedes Mal neu zu erfinden, wenn Sie dies benötigen Bit-Manipulation durchführen.
Testen bzw. erweitere den folgenden Code:
#include "mbed.h"
BusOut myleds(LED1, LED2, LED3, LED4);
#define BOOL(x) (!(!(x)))
#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))
int bitmanip(int word) {
word = BitSet(word, 2);
word = BitSet(word, 7);
word = BitClr(word, 3);
word = BitFlp(word, 9);
return word;
}
int main() {
uint16_t mask = 0x000f; // 00000000 00001111b mask lower Nibble
uint16_t value = 0x0055; // 00000000 01010101b
while(1) {
scanf("%d", &value);
value=bitmanip(value);
value=BitSet(value, 8);
myleds = value & mask;
printf("%x\n", value)
wait(0.25);
}
}