Expecco Code Snippets/en
Version vom 18. September 2020, 13:16 Uhr von Cg (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „== Code Snippets for Common Tasks == === Bits & Bytes === ==== Set, Clear or Toggle a Bit ==== Smalltalk: |numIn result| numIn := 0b10011001. "/ using m…“)
Inhaltsverzeichnis
Code Snippets for Common Tasks[Bearbeiten]
Bits & Bytes[Bearbeiten]
Set, Clear or Toggle a Bit[Bearbeiten]
Smalltalk:
|numIn result|
numIn := 0b10011001. "/ using masks result := numIn bitOr: 0b00110000. "/ to set the two bits result := numIn bitAnd: 0b11110000. "/ to mask bits result := numIn bitClear: 0b00000011. "/ to clear bits result := numIn bitXor: 0b00001100. "/ to toggle bits result := numIn bitTest: 0b00001100. "/ to test if masked bits are all set
"/ using bit numbers (index starts with 1 for the least significant bit) result := numIn bitAt: 1. "/ to extract the first bit result := numIn setBit: 2. "/ set the second bit result := numIn clearBit: 2. "/ clear the second bit result := numIn invertBit: 2. "/ toggle the second bit
JavaScript:
var numIn, result;
numIn = 0b10011001; // using masks result = numIn | 0b00110000; // to set the two bits result = numIn & 0b11110000; // to mask bits result = numIn & ˜0b00000011; // to clear bits result = numIn ^ 0b00001100; // to toggle bits result = (numIn & 0b00001100) != 0; // to test if masked bits are all set
// using bit numbers (index starts with 1 for the least significant bit) result := numIn.bitAt(1); // to extract the first bit result := numIn.setBit(2); // set the second bit result := numIn.clearBit(2); // clear the second bit result := numIn.invertBit(2); // toggle the second bit