Expecco Code Snippets/en
Version vom 18. September 2020, 13:29 Uhr von Cg (Diskussion | Beiträge) (→Set, Clear or Toggle a Bit)
Inhaltsverzeichnis
Code Snippets for Common Tasks[Bearbeiten]
This page provides code snippets for common tasks. You can copy-paste these snippets into the code editor and modify as appropriate. You can also paste them into a Workspace window and execute them there. Finally, you may also find those snippets via the Method Finder, when entering the desired result value.
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
Shifting[Bearbeiten]
Smalltalk:
|numIn result| numIn := 0xABCD. result := numIn bitShift: 8. "/ left shift by 8 result := numIn bitShift: -8. "/ right shift by 8 result := numIn << 8. "/ alternative left shift result := numIn >> 8. "/ alternative right shift
JavaScript:
var numIn, result; numIn = 0xABCD; result = numIn << 8; // left shift by 8 result = numIn >> 8; // right shift by 8