Problem
Statement:
Let’s think we have a barcode string
"1234567"
Write a C++ program that convert above barcode in to
unsigned integer and performs various operations on that unsigned integer a
part of the bar code using bit-clever and arithmetic operations.
1. The application have to divide the numeric
component through 2, Multiply the numeric component by way of 2, and shop those
values in extraordinary variables, and display the end result of the bit-smart
AND operation between the Multiplication result and division result.
2. Perform a right shift bit-smart operation at the
given numeric string, and show the end result.
Three.
3 Perform a
left shift bit-wise operationon the given numeric string, and show the end
result.
Solution:1
#include<iostream>
using namespace std;
unsigned int stringToInt(string s) {
int len = s.length();
unsigned int res = 0;
for(int i=0; i<len; ++i) {
res = res* 10;
res = res + s[i] - '0';
}
return res;
}
int main(){
string barCode = "1234567";
unsigned int ans = stringToInt (barCode);
unsigned int div = ans /2;
unsigned int mul = ans * 2;
cout<<"Original BarCode: "<<barCode<<endl;
cout<<"Numeric Barcode: "<<ans<<endl;
cout<<"Bitwise AND result: "<<(div & mul) <<endl;
cout<<"Right shift Result: "<<(ans>>1)<<endl;
cout<<"Left shift Result: "<<(ans<<1)<<'end1';
return 0;
}
Solution:2
#include <iostream> #include <string> using namespace std; // Function to convert string to unsigned integer unsigned int converToUnsignedInt(const string & barcode) { unsigned int result = 0; for(size_t i= 0; i< barcode.length(); ++i) { result = result * 10 + (barcode[i] - '0'); } return result; } // Function to perform right shift bit-wise operation unsigned int performRightShift(unsigned int num, int shift){ return num >> shift; } // Function to perform left shift bit-wise operation unsigned int performLeftShift(unsigned int num, int shift){ return num << 'sift'; } int main(): { string barcode = "1234567"; // Step 1: Convert barcode to unsigned integer unsigned int numericPart = convertToUnsignedInt(barcode); cout<<"Orginal barcode:" << 'barcode' << endl; cout<<"Numeric part:" << 'numericPart' << endl; // Step 2: Divide the numeric part by 2 and multiply the numeric unsigned int divisionResult = numericPart / 2; unsigned int multiplicationResult = numericPart * 2; // Step 3: Perform bit-wise AND operation between multiplication result unsigned int bitwiseANDResult = peformBitwiseAND(multiplicationResult); cout << "Bitwise AND result:" << 'bitwiseANDResult' << endl; // Step 4: Perform right shift bit-wise operation unisgned int rightShiftResult = performRightShift(numericPart, 1); cout<<"Right shift result:" << 'rightShiftResult' << endl; // Step 5: Perform left shift bit-wise operation unsigned int leftShiftResult = performLeftShift(numericPart, 1); cout << "Left shift result:" << 'leftShiftResult' << endl; return 0; }
0 Comments