C++ Online Compiler
Example: Bitwise Right Shift Example in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Bitwise Right Shift Example #include <iostream> #include <bitset> // For binary representation int main() { unsigned int positiveNum = 40; // Binary: 00101000 int negativeNum = -40; // Example (system dependent): 11011000 (Two's complement for 8-bit) std::cout << "Original positive number: " << positiveNum << " (Binary: " << std::bitset<8>(positiveNum) << ")" << std::endl; // Shift right by 1 position (40 / 2^1 = 20) unsigned int shiftedRight1 = positiveNum >> 1; std::cout << "Shifted right by 1: " << shiftedRight1 << " (Binary: " << std::bitset<8>(shiftedRight1) << ")" << std::endl; // Shift right by 3 positions (40 / 2^3 = 5) unsigned int shiftedRight3 = positiveNum >> 3; std::cout << "Shifted right by 3: " << shiftedRight3 << " (Binary: " << std::bitset<8>(shiftedRight3) << ")" << std::endl; std::cout << "\nOriginal negative number: " << negativeNum << " (Binary: " << std::bitset<8>(negativeNum) << ")" << std::endl; int shiftedNegative = negativeNum >> 1; // Arithmetic shift (preserves sign) std::cout << "Shifted negative by 1: " << shiftedNegative << " (Binary: " << std::bitset<8>(shiftedNegative) << ")" << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS