Can I manipulate output stream this way? [duplicate] - c++

This question already has answers here:
decimal to 8 bit binary conversion in c++
(3 answers)
Closed 9 years ago.
I was trying to print an integer in binary format using output stream manipulators in C++ but I was unsuccessful in doing so.
I tried using the following code to manipulate the base.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int binary, gray;
cin >> binary;
cout << std::setbase(2) << (binary >> 1);
}
But I guess only decimal, hexadecimal and octal bases are supported in this manipulator.
Is there any way I can print an integer in binary format using manipulators in iomanip header?

Use bitset i.e.
cout << bitset<16>(10).toString() << endl;

std::setbase only supports bases of 8, 10, or 16. You can use std::bitset<N> to print out the binary representation yourself however:
#include <bitset>
int main()
{
std::cout << std::bitset<16>(0x1F); // 0000 0000 0001 1111
}

#include <bitset>
#include<iostream>
int main(){
int i=13;
std::bitset<8> bit (i);
std::cout<<bit.to_string();
return 0;
}
result:
00001101
cout<<bitset<8>(0xd).to_string();
gives the same

Related

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

Convert std::string number in hexadecimal number [duplicate]

This question already has answers here:
C++ convert hex string to signed integer
(10 answers)
Closed 8 years ago.
I have searched online, but it doesn't seem to be a solution to my problem. Basically I have a std::string which contains a hexadecimal memory address (like 0x10FD7F04, for example). This number is read from a text file and saved as a std::string, obviously.
I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?
You can use C++11 std::stoi function:
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
std::string your_string_rep{"0x10FD7F04"};
int int_rep = stoi(your_string_rep, 0, 16);
std::cout << int_rep << '\n';
std::cout << std::hex << std::showbase << int_rep << '\n';
}
Outputs:
285048580
0x10fd7f04
I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?
There are two parts to your question:
Convert the string hexadecimal representation to an integer.
std::string your_string_rep{ "0x10FD7F04" };
std::istringstream buffer{ your_string_rep };
int value = 0;
buffer >> std::hex >> value;
Keeping the hex notation on the resulting value. This is not necessary/possible, because an int is already a hexadecimal value (and a decimal value and a binary value, depending on how you interpret it).
In other words, with the code above, you can just write:
assert(value == 0x10FD7F04); // will evaluate to true (assertion passes)
Alternatively you can use something like this
std::string hexstring("0x10FD7F04");
int num;
sscanf( hexstring.data(), "%x", &num);

Convert binary bitset to hexadecimal (C++)

Is there a simple way to convert a binary bitset to hexadecimal? The function will be used in a CRC class and will only be used for standard output.
I've thought about using to_ulong() to convert the bitset to a integer, then converting the integers 10 - 15 to A - F using a switch case. However, I'm looking for something a little simpler.
I found this code on the internet:
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
int main(){
string binary_str("11001111");
bitset<8> set(binary_str);
cout << hex << set.to_ulong() << endl;
}
It works great, but I need to store the output in a variable then return it to the function call rather than send it directly to standard out.
I've tried to alter the code but keep running into errors. Is there a way to change the code to store the hex value in a variable? Or, if there's a better way to do this please let me know.
Thank you.
You can send the output to a std::stringstream, and then return the resultant string to the caller:
stringstream res;
res << hex << uppercase << set.to_ulong();
return res.str();
This would produce a result of type std::string.
Here is an alternative for C:
unsigned int bintohex(char *digits){
unsigned int res=0;
while(*digits)
res = (res<<1)|(*digits++ -'0');
return res;
}
//...
unsigned int myint=bintohex("11001111");
//store value as an int
printf("%X\n",bintohex("11001111"));
//prints hex formatted output to stdout
//just use sprintf or snprintf similarly to store the hex string
Here is the easy alternative for C++:
bitset <32> data;
/*Perform operation on data*/
cout << "data = " << hex << data.to_ulong() << endl;

Cannot convert from string to hexadecimal [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ convert hex string to signed integer
I have the string line which is a hexadecimal number say like 12ab43c..(but I have read it as a string) and I would like to pass it to an unsigned char* linehex or directly to a hexadecimal so I can later use it in my program for further computations.
Which is the most efficient way to do this?
The easiest is probably to read it as a number to start with, instead of reading it as a string, then converting. For example:
some_stream >> std::hex >> your_number;
Quick demo code:
#include <iostream>
int main() {
int x;
std::cin >> std::hex >> x;
std::cout << x << "\n";
return 0;
}
Input: ff
Output: 255

Write BitSet of 8 bits to file (C++)

I have a BitSet of 8 bits.
How would I convert those 8 bits to a byte then write to file?
I have looked everywhere and only find converting the other way.
Thanks alot!
Assuming that you are talking about C++ STL bitsets, the answer is to convert the bitset to int (ulong to be precise), and casting the result into a char.
Example:
#include <bitset>
#include <iostream>
using namespace std;
main()
{
bitset<8> x;
char byte;
cout << "Enter a 8-bit bitset in binary: " << flush;
cin >> x;
cout << "x = " << x << endl;
byte = (char) x.to_ulong();
cout << "As byte: " << (int) byte << endl;
}
http://www.cplusplus.com/reference/stl/bitset/
They can also be directly inserted and extracted from streams in binary format.
You don't need to convert anything, you just write them to the output stream.
Aside from that, if you really wanted to extract them into something you're used to, to_ulong and to_string methods are provided.
If you have more bits in the set than an unsigned long can hold and don't want to write them out directly to the stream, then you're either going to have convert to a string and go that route, or access each bit using the [] operator and shift them into bytes that you're writing out.
You could use fstream std::ofstream:
#include <fstream>
std::ofstream os("myfile.txt", std::ofstream::binary);
os << static_cast<uint_fast8_t>(bitset<8>("01101001").to_ulong());
os.close();