How to output the Binary value of a variable in C++ - c++

I've got a homework assignment in my C++ programming class to write a function that outputs the binary value of a variable's value.
So for example, if I set a value of "a" to a char I should get the binary value of "a" output.
My C++ professor isn't the greatest in the whole world and I'm having trouble getting my code to work using the cryptic examples he gave us. Right now, my code just outputs a binary value of 11111111 no matter what I set it too (unless its NULL then I get 00000000).
Here is my code:
#include <iostream>
#define useavalue 1
using namespace std;
void GiveMeTehBinary(char bin);
int main(){
#ifdef useavalue
char b = 'a';
#else
char b = '\0';
#endif
GiveMeTehBinary(b);
system("pause");
return 0;
}
void GiveMeTehBinary(char bin){
long s;
for (int i = 0; i < 8; i++){
s = bin >> i;
cout << s%2;
}
cout << endl << endl;
}
Thanks a ton in advance guys. You're always extremely helpful :)
Edit: Fixed now - thanks a bunch :D The problem was that I was not storing the value from the bit shift. I've updated the code to its working state above.

The compiler should warn you about certain statements in your code that have no effect1. Consider
bin >> i;
This does nothing, since you don’t store the result of this operation anywhere.
Also, why did you declare tehbinary as an array? All you ever use is one element (the current one). It would be enough to store just the current bit.
Some other things:
NULL must only be used with pointer values. Your usage works but it’s not the intended usage. What you really want is a null character, i.e. '\0'.
Please use real, descriptive names. I vividly remember myself using variables called tehdataz etc. but this really makes the code hard to read and once the initial funny wears off it’s annoying both for you when you try to read your code, and for whoever is grading your code.
Formatting the code properly helps understanding a lot: make the indentation logical and consistent.
1 If you’re using g++, always pass the compiler flags -Wall -Wextra to get useful diagnostics about your code.

Try this:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<8> x('a');
std::cout << x << std::endl;
}

it's actually really simple. to convert from decimal to binary you will need to include #include <bitset> in your program. inside here, it gives you a function that allows you to convert from decimal to binary form. and the function looks like this:
std::cout << std::bitset<8>(0b01000101) << std::endl;
the number 8 in the first argument means the length of the output string. the second argument is the value you want to convert. by the way, you can input a variable in binary form by declaring a 0b in front of the number to write it in binary form. note that to write in binary form is a feature added in c++14 so using any version lower than that won't work. here is the full code if you want to test it out.
#include <iostream>
#include <bitset>
int main()
{
std::cout << std::bitset<8>(0b01000101) << std::endl;
}
note that you don't have to input a binary number to do this.
#include <iostream>
#include <bitset>
int main()
{
std::cout << std::bitset<8>(34) << std::endl;
}
output:
00100010

Why not just check each bit in the unsigned char variable?
unsigned char b=0x80|0x20|0x01; //some test data
int bitbreakout[8];
if(b&0x80) bitbreakout[7]=1;
//repeat above for 0x40, 0x20, etc.
cout << bitbreakout;
There are a TON of ways to optimize this, but this should give you an idea of what do to.

#include <iostream>
using namespace std;
int main(){
int x = 255;
for(int i = numeric_limits<int>::digits; i >=0; i--){
cout << ((x & (1 << i)) >> i);
}
}

it's actually really simple. if you know how to convert decimal to binary, then you can code it easily in c++. in fact I have gone ahead and created a header file that allows you not only to convert from decimal to binary, it can convert from decimal to any number system. here's the code.
#pragma once
#include <string>
char valToChar(const uint32_t val)
{
if (val <= 9)
return 48 + val;
if (val <= 35)
return 65 + val - 10;
return 63;
}
std::string baseConverter(uint32_t num, const uint32_t &base)
{
std::string result;
while (num != 0)
{
result = valToChar(num % base) + result;
num /= base;
}
return result;
}
now, here is how you can use it.
int main()
{
std::cout << baseConverter(2021, 2) << "\n";
}
output:
11111100101

Related

how to take a double's fraction part and turn it into an integer? (c++)

my goal is to turn a double's fraction part into an integer, for example: turn 0.854 into 854 or turn 0.9321 into 9321 (the whole part of the double is always 0)
i was doing it like this, but i dont know how to fill the while's parameters to make it stop when variable x becomes a whole number without a fraction:
double x;
cin >> x;
while(WHAT DO I TYPE HERE TO MAKE IT STOP WHEN X BECOMES A WHOLE NUMBER){
x *= 10;
}
it would be best if i could do it with a loop, but if it is not possible, i am open to other suggestions :)
That question has no answer in a mathematical/logical sense. You have to read how floating point numbers in computers work, see e.g.
https://en.wikipedia.org/wiki/Floating-point_arithmetic
and understand that they are not decimal point numbers in memory. A floating point number in memory consists of three actual numbers: significant * base^{exponent} and according to IEEE the base used is "2" in basically any modern floating point data, but in even more generality, the base can be anything. Thus, whatever you have in your mind, or even see on your screen as output, is a misleading representation of the data in memory. Your question is, thus, mainly a misconception of how floating point numbers in computers work...
Thus, what you specifically ask for does in general not exist and cannot be done.
However, there may be special application for output formatting or whatever where something like this may make sense -- but then the specific goal must be clearly stated in the question here. And in some of such cases, using a "string-based" approach, as you suggested, will work. But this is not an answer to your generic question and has the high potential to also mislead others in the future.
Actually, one way to make your question obvious and clear is to also specify a fixed desired precision, thus, numbers after the decimal point. Then the answer is quite trivially and correctly:
long int value = fraction * pow(10, precision);
In this scenario you know 100% what your are doing. And if you really like you could subsequently remove zeros from the right side...
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
However there is another principle problem on a numerical level: there is no mathematical difference between, e.g., 000003 and just 3, thus in any such application the input 0.000003 will give the same results as 0.0003 or 0.3 etc. This cannot be a desired functionality... it is pretty useless to ask about the *value of the fractional part of a floating point number. But, since we have a known precision`, we can do:
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
which will fill in the eventually missing leading zeros.
See this complete tested test code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double v = 0.0454243252;
int precision = 14;
long int value = v*pow(10,precision);
cout << value << endl;
// 4542432520000
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
cout << value << endl;
// 454243252
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
// 0454243252
}
Here is a possible approach:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Enter Number: ";
double user_input;
cin >> user_input;
int user_input_to_int = int(user_input);
double decimal_value = user_input - user_input_to_int;
ostringstream oss;
oss << std::noshowpoint << decimal_value;
string num_str = oss.str();
int str_length = num_str.size()-2;
int multiplier = 1;
for (int x = 0; x < str_length; x++)
{
multiplier *= 10;
}
cout << "\n";
cout << "Whole number: " << user_input_to_int << endl;
cout << "Decimal value: " << decimal_value*multiplier << endl;
}
Compare the difference between double and integer part. It is working only if x is less than 2^63.
while (x - long long(x) > 0)
find 2 real numbers find the fractional part smaller than these numbers

How to convert char(or string, other type) -> bits?

In c++,
I don't understand about this experience. I need your help.
in this topic, answers saying use to_string.
but they say 'to_string' is converting bitset to string and cpp reference do too.
So, I wonder the way converting something data(char or string (maybe ASCII, can convert unicode?).
{It means the statement can be divided bit and can be processed it}
The question "How to convert char to bits?"
then answers say "use to_string in bitset"
and I want to get each bit of my input.
Can I cleave and analyze bits of many types and process them? If I can this, how to?
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main() {
char letter;
cout << "letter: " << endl;
cin >> letter;
cout << bitset<8>(letter).to_string() << endl;
bitset<8> letterbit(letter);
int lettertest[8];
for (int i = 0; i < 8; ++i) {
lettertest[i] = letterbit.test(i);
}
cout << "letter bit: ";
for (int i = 0; i < 8; ++i) {
cout << lettertest[i];
}
cout << endl;
int test = letterbit.test(0);
}
When executing this code, I get result I want.
But I don't understand 'to_string'.
An important point is using of "to_string"
{to_string is function converting bitset to string(including in name),
then Is there function converting string to bitset???
Actually, in my code, use the function with a letter -> convert string to bitset(at fitst, it is result I want)}
help me understand this action.
Q: What is a bitset?
https://www.cplusplus.com/reference/bitset/bitset/
A bitset stores bits (elements with only two possible values: 0 or 1,
true or false, ...).
The class emulates an array of bool elements, but optimized for space
allocation: generally, each element occupies only one bit (which, on
most systems, is eight times less than the smallest elemental type:
char).
In other words, a "bitset" is a binary object (like an "int", a "char", a "double", etc.).
Q: What is bitset<>.to_string()?
Bitsets have the feature of being able to be constructed from and
converted to both integer values and binary strings (see its
constructor and members to_ulong and to_string). They can also be
directly inserted and extracted from streams in binary format (see
applicable operators).
In other words, to_string() allows you to convert the binary bitset to text.
Q: How to to I convert convert char(or string, other type) -> bits?
A: Per the above, simply use bitset<>.to_ulong()
Here is an example:
https://en.cppreference.com/w/cpp/utility/bitset/to_string
Code:
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b(42);
std::cout << b.to_string() << '\n'
<< b.to_string('*') << '\n'
<< b.to_string('O', 'X') << '\n';
}
Output:
00101010
**1*1*1*
OOXOXOXO

I am trying to solve timus reverse root (1001) problem and facing the following problem

#include <iostream>
#include <cmath>
double buf[128 * 1024];
int main()
{
int i = 0;
unsigned long long n; // 64-bit unsigned integer
while (std::cin>>n) {
buf[i ++] = double(sqrt(n)); // store in buffer
}
i--;
while(i>=0){
printf("%lf\n",buf[i]); // When i am using this it works fine.
//std::cout<<buf[i]<<std::endl; // When i am using this line instead of printf function it shows wrong answer. why?
i--;
}
return 0;
}
I have compiled it with G++.
While I am trying to print the output with printf funtion then it is accepted. But when I am using cout function then it gives wrong answer. Why is it happened?
This code shows compilation error when i am compiling it in GCC7.1 . What is the reason of this?
Problem Link : https://acm.timus.ru/problem.aspx?space=1&num=1001
Using the << operator with std::cout rounds to 6 significant figures by default and uses scientific notation for large floating point numbers. To disable the scientific notation, include the <iomanip> header and use std::cout << std::fixed << buf[i];. Using std::fixed will also set the rounding to 6 digits after the decimal point.

why in decimal to binary code it does not work properly when we enter numbers above 63?

i wrote a code that recives the numbers from the base ten and gives us the binary number.But for numbers above 64, it just doesn't work properly.and i don't know why.please help me.
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int c; int b,a[c];
cin>>b;
for(c=0;b>1;c++)
{
a[c]=b%2;
b=b/2;
}
cout<<b;
c--;
for(c;c>=0;c--){
cout<<a[c];
}
getch();
The problem resides here:
int c; int b,a[c];
You are defining a Variable Length Array (not standard, btw) of size c, but you have not given c a value, therefore, this is undefined behaviour (use of c before giving it a value). Since you are dealing with integers, you can do int a[32] though, which should allow your code to work.
Another method with strings:
std::string str;
while ( b != 0 ) {
str = std::to_string( b % 2 ) + str;
b /= 2;
}
std::cout << str;
A few things to note:
main requires a return type, and should be int main()
conio.h is not standard, and shouldn't be used
int a[c] is a variable length array (VLA), not standard, and shouldn't be used.
using namespace std is a bad idea.
The problem has been pointed out in other answers so I'm just going to give you an alternative solution.
You could also try using bitset if your intent is to convert to binary.
#include <bitset>
using namespace std;
bitset<32> bv;
bv = 65;
cout << "Binary value " << bv <<"\n";
bv = 195;
cout << "Binary value " << bv <<"\n";

Strange output from C++ in Linux Terminal

I've recently started learning programming using the C++ language. I wrote a simple program that is supposed to reverse a string which I compile in the Terminal using gcc/g++.
#include <iostream>
using namespace std;
string reverse_string(string str)
{
string newstring = "";
int index = -1;
while (str.length() != newstring.length())
{
newstring.append(1, str[index]);
index -= 1;
}
return newstring;
}
int main()
{
string x;
cout << "Type something: "; cin >> x;
string s = reverse_string(x);
cout << s << endl;
return 0;
}
I've rewritten it multiple times but I always get the same output:
Type something: banana
��
Has anyone had a problem like this or know how to fix it?
Your code initializes index to -1, and then uses str[index] but a negative index has no rational meaning in C++. Try instead initializing it like so:
index = str.length() - 1;
I can see several issues with your code. Firstly, you are initializing index to -1, and then decrementing it. Maybe you meant auto index = str.length()-1;?
I recommend you look at std::reverse, which will do the job you're after.
Your main function then becomes:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x;
cout << "Type something: ";
cin >> x;
reverse(x.begin(), x.end());
cout << x << endl;
return 0;
}
If you really want to write your own reverse function, I recommend iterators over array indices. See std::reverse_iterator for another approach.
Note, the above will simply reverse the order of bytes within the string. Whilst this is fine for ASCII, it will not work for multi-byte encodings, such as UTF-8.
You should use a memory debugger like valgrind.
It's a good practice to scan your binary with it, and will make you save so much time.