Can some explain the logic for this output? - c++

I am printing a string (created by bitset in stl) and then printing the string directly and by using loop why there is difference in the output?
#include<iostream>
#include<bitset>
using namespace std;
int main()
{
const int m=16;
int n;
int arr[m];
cin>>n;
bitset<m>bt(n);
cout<<bt<<endl;
for(int i=0;i<m;i++)
{
cout<<bt[i];
}
}
Input:
995
Output:
0000001111100011 //Printing string
1100011111000000 //Printing using loop
The output of one is reverse the other .
I do not understand why this is happening?

cout << bt << endl;
The above prints the number as desired
cout << bt[0] << endl;
however, when we index a bitmap, the indexing starts from the rightmost bit, or the LSB.
As quoted on http://www.cplusplus.com/reference/bitset/bitset/operator[]/
Order positions are counted from the rightmost bit, which is order position 0.

It is consistent with the way bits are usually numbered, [0] represents the LSB(least significant bit). When you convert bitset to string — it will contain bits the opposite order, with first character corresponding to N-1th bit.

Related

How do I input 2 variables in one line and count them in output?

Out of all activity I've been tasked with, this was by far one of the most challenging one.
I am an IT student, ie a beginner in the C++ language, and so far I've only been taught how to make use of while loops and if conditions. By this, we have to use these two in the following activity:
Count how many of a certain digit is present on a given number.
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result (see sample input and output for example).
In short, a program that reads the first value and checks how many of this first value is present in the second value.
Supposed Input: 2 1242182
Expected Output: 3
As you can see, it counts how many 2s are present in the second value (1242182). The result is 3 since there are three 2s present in it.
I find it impossible to create a program that can read 2 values in one line just using if conditions and a while loop, but this was given by us from an official programming website.
It should look like this.
#include <iostream>
using namespace std;
int main() {
int v1;
cin >> v1;
if (...) {
....
}
while (...) {
...
}
return 0;
}
Also, no using arrays.
#include <iostream>
using namespace std;
int main() {
int v1, v2;
cin >> v1 >> v2;
}
You need to get the two numbers, and then convert the second one to a string and iterate through that, checking it and incrementing.
#include <iostream>
#include <string>
using namespace std;
int main(){
int number, count, digit;
string num;
cin >> number >> num;
for(int i = 0; i < num.length(); i++){
digit = stoi(num[i]);
if(number == digit){
count++;
}
}
cout << "count: " << count << "\n";
}

Difference in bitset<10> and bitset<2>(input[i]) , need explanation

I just learned some simple encryption today and wrote a simple program to convert my text to 10-bit binary. Im not sure if i'm doing it correctly, but the commented section of the code and the actual code has 2 different 10-bit outputs. I am confused. Can someone explain it to me in layman terms?
#include <iostream>
#include <string>
#include <bitset>
#include "md5.h"
using namespace std;
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
string input ="";
cout << "Please enter a string:\n>";
getline(cin, input);
cout << "You entered: " << input << endl;
cout << "md5 of " << input << ": " << md5("input") << endl;
cout << "Binary is: ";
// cout << bitset<10>(input[1]);
for (int i=0; i<5; i++)
cout << bitset<2>(input[i]);
cout << endl;
return 0;
}
tl;dr : A char is 8 bits, and the string operator[] returns the different chars, as such you accessed different chars and took the first two bits of those. The solution comes in treating a char as exactly that: 8 bits. By doing some clever bit manipulation, we can achieve the desired effect.
The problem
While I still have not completely understood, what you were trying to do, I can answer what a problem could be with this code:
By calling
cout<<bitset<10>(input[1]);
you are reading the 10 bits starting from the second character ( input[0] would start from the first character).
Now, the loop does something entirely different:
for (int i=0; i<5; i++)
cout << bitset<2>(input[i]);
It uses the i-th character of the string and constructs a bitset from it.
The reference of the bitset constructor tells us this means the char is converted to an unsigned long long, which is then converted to a bitset.
Okay, so let's see how that works with a simple input string like
std::string input = "aaaaa";
The first character of this string is 'a', which gives you the 8 bits of '01100001' (ASCII table), and thus the 10 bit bitset that is constructed from that turns out to print
0001100001
where we see a clear padding for the bits to the left (more significant).
On the other hand, if you go through the characters with your loop, you access each character and take only 2 of the bits.
In our case of the character 'a'='01100001', these bits are '01'. So then your program would output 01 five times.
Now, the way to fix it is to actually think more about the bits you are actually accessing.
A possible solution
Do you want to get the first ten bits of the character string in any case?
In that case, you'd want to write something like:
std::bitset<10>(input[0]);
//Will pad the first two bits of the bitset as '0'
or
for(int i=0;i<5;++i){
char referenced = input[i/4];
std::bitset<2>((referenced>>(6-(i%4)*2)));
}
The loop code was redesigned to read the whole string sequentially into 2 bit bitsets.
So since in a char there are 8 bits, we can read 4 of those sets out of a single char -> that is the reason for the "referenced".
The bitshift in the lower part of the loop makes it so it starts with a shift of 6, then 4, then 2, then 0, and then resets to 6 for the next char, etc...
(That way, we can extract the 2 relevant bits out of each 8bit char)
This type of loop will actually read through all parts of your string and do the correct constructions.
A last remark
To construct a bitset directly from your string, you would have to use the raw memory in bits and from that construct the bitset.
You could construct 8 bit bitsets from each char and append those to each other, or create a string from each 8 bit bitset, concatenate those and then use the final string of 1 and 0 to construct a large bitset of arbitrary size.
I hope it helped.

I am having problems with arrays in my code. Any suggestions?

Here is my code for my main.cpp:
#include <iostream>
using namespace std;
int main()
{
int input1[8];
int input2[8];
int output[8];
cout << "Welcome to binary calculator!" << endl;
cin >> input1[8];
cin >> input2[8];
if(input1[0]+input2[0]>1){
output[8] = 0;
if(input1[1]+input2[1]>1){
output[7] = 0;
cout << output[7] << output[8] << endl;
}
}else{
output[8]=input1[8]+input2[8];
}
return 0;
}
My problem is that on the line where the 8th element of output is supposed to equal the sum of the 8th element of input1 and the 8th element of input2. I tried to put seven because I thought I remembered that was how indexing for arrays worked but I was wrong, and now I am stuck.
If you are trying to manipulate the 8th element of an array, it should be accessed using input1[7]/input2[7], as the array index always start from 0.
Please elaborate more as to what exactly is the problem you are facing.
Are you supposed to read in integers and manipulate the bits?
Bit manipulation, or twiddling, is performed using the binary operators: &, |, ~, ^, +, and -.
See also: std::bitset which helps treat a number as a container of bits.
Binary arithmetic is too large of a concept to explain in a Stack Overflow answer; search the internet for "C++ binary arithmetic tutorial".

Binary numbers with leading zeros

I've been working on an assignment where I've to use bitwise operators to (OR, AND, or NOT )
the Program has a fixed 4X4 matrix and the user suppose to enter a query to the program ANDing two BINARY numbers, ORing them ...etc
the problem is the "zero leading" binary numbers for example:0111 are shown with value 73
even when I manage to cout it with setfill() and setw()
I can't perform the bitwise operation on the actual binary value!
N.B: I've tried strings instead of ints but the bitwise operation still doesn't apply.
For Example:
if I want to AND two binary values let's say
int x=1100 and int y=0100 in another int z
z=x&y;
the result suppose to be 0100
But the result that appears is 64
which also the result that appears if I tried to print y to the screen
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int Matrix[4][4]={{1,1,0,0},{1,1,0,1},{1,1,0,1},{0,1,0,0}};
string Doc[4]={"Doc1","Doc2","Doc3","Doc4"};
string Term[4]={"T1","T2","T3","T4"};
cout << "THE MATRIX IS:"<<endl;
for(int i=0;i<4;i++)
{
cout<<"\t"<<Doc[i];
}
cout<<"\n";
for(int row=0; row<4;row++)
{
cout<<Term[row]<<"\t";
for(int col=0;col<4;col++)
{
cout<<Matrix[row][col]<<"\t";
}
cout<<endl;
}
int term1=1100;
cout<<"\nTerm1= "<<term1;
int term2=1101;
cout<<"\nTerm2= "<<term2;
int term3=1101;
cout<<"\nTerm3= "<<term3;
int term4=0100;
cout<<"\nTerm4= "<<setfill('0')<<setw(4)<<term4;
int Q=term1&term4;
cout<<"\n Term1 and Term4 ="<<Q;
system("pause");
return 0;
}
When you write 0111 in your code the compiler will assume it's octal since octal numbers start with zero. If you wrote 111 it would be decimal.
C++14 added binary literal prefix so you can write 0b111 to get what you want.
Your question still not clear. You have said you have 4x4 matrix, what type of matrix or 2D array is it? So maybe you can elaborate more.
Regarding dealing with binaries, what students usually confuse about, is that if you are using integer variables, you can use bitwise manipulation over these variables and the result will still be read as an integer format. And if you happen to seek seeing what is happening during the bitwise manipulation and visualize the process, you can always use bitset object as follow.
#include <iostream>
#include <bitset>
int main() {
int a = 7, b = a>>3, c = a<<2;
std::cout << "a = " << std::bitset<8>(a) << std::endl;
std::cout << "b = " << std::bitset<8>(b) << std::endl;
std::cout << "c = " << std::bitset<8>(c) << std::endl;
}
Which should print
00000111
00000000
00011100
So play around with your variables and then visualize them as binaries using bitset is the best way to teach you how HEX, OCT, DEC, and BIN representation works.
And by the way if you are reading 73 as an integer, then this memory address stores 0100 1001 as binary if it's unsigned, and 111 as Octal which is base 8 number representation. See http://coderstoolbox.net/number/
Best of luck

Using C++ how many characters are in a string array?

I have the below piece of code and I'm very confused by it. I'm trying to figure out how much memory (bytes of memory/space is actually being taken up by my partially filled array). I've got the below piece of code but I'm a bit confused.
If I declare a string array of 8 elements, and partially fill the elements with the two strings. The for loop will start at 0 and go until size of my array 32 possible bytes (assuming I need 4 bytes per string) divided by size of the first element in the array. That is returns 4 - the size of the element of the first string in the array. But that still doesn't tell me how many letters/characters are in that string.
I understand inside the loop we increment count when the value in the array doesn't equal a blank/null value. Giving us the total filled (non empty) positions in our array. However I still don't have a value for our actual amount of characters.
How does this tell us how many characters are in my strings?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string test_array[8] = {"henry", "henry2"};
size_t count = 0;
for (size_t i = 0; i < sizeof(test_array)/sizeof(*test_array); i++)
{
cout << "NOT THE POINTER: "<<sizeof(test_array) << endl;
cout << "POINTER: "<<sizeof(*test_array) << endl;
if(test_array[i] != "")
count ++;
}
int num_elem = sizeof(test_array)/sizeof(test_array[0]);
cout << num_elem << endl;
cout << count << endl;
return 0;
}
To know how many characters are in a std::string use the size() method.