C++ - How to get a binary representation of a decimal number [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to get the binary representation of a decimal number. I have looked all over the internet but could not find anything useful.
Can anyone provide me with sample code?
Note that I want it to run on both 32-bit and 64-bit architecture.
Thanks!

Just isolate the bits one by one, starting from the highest, and print the appropriate character:
#include <limits.h>
#include <stdio.h>
void print_binary(unsigned x)
{
for (int i = sizeof(x) * CHAR_BIT; i--; )
{
putchar('0' + ((x >> i) & 1));
}
}
int main()
{
print_binary(123);
}
If you want the result in a string instead of printed to the console, I'm sure you can adjust the code.

Get the bits from the bottom up.
Then reverse the string when done.
string bits(long n)
{
string tmp ;
while ( n ) { tmp << ( n & 1 ) ? "1" : "0" ; n >>= 1 ; }
tmp= reverse( tmp) ;
return tmp ;
}

Try William Clinger's paper "How to read floating point numbers accurately".

Related

Number of distinct elements in array using bits in int [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have this code
what is wrong in my code
it must display how many distinct elements are there
string name;
long long maps;
int i,j,test,l,counts=0,k;
cin>>test;
for(i=0;i<test;i++){
counts=maps=0;
cin>>name;
l = name.length();
for(j=0;j<l;j++){
k=(toupper(name[j])-'A');
cout<<endl<<(maps&(1<<k))<<" "<<k;
if(0 == maps&(1<<k)){
counts++;
maps|=(1<<k);
}else{
cout<<" "<<(int)(maps&(1<<k))==0;
}
}
cout<<counts;
}
what is wrong check witht the output i cant find why i is not working
The problem is here:
if(0 == maps&(1<<k)){
The equality operator == has higher precedence than the bitwise-AND operator &. So the above evaluates to this:
if ((0 == maps) & (1 << k )) {
You need to add parenthesis to get the desired behavior:
if (0 == (maps & (1 << k))) {
You'll need to do the same in your cout call:
cout<<" "<<(int)((maps&(1<<k))==0);

Truncate an int value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I want to make a function which takes an integer with the number like 113, and separates the one's digit "3" and and the hundreds and tens places "11" and returns the both of them in two separate integers.
x%10 for the first digit (from right) and x/10 for the rest.
#include <iostream>
#include <utility>
std::pair<int,int> split(int x)
{
return std::make_pair(x/10, x%10);
}
int main()
{
std::pair<int,int> z = split(113);
std::cout << z.first << " " << z.second;
}
I also used std::pair to return the result.
You want N % 10 to get the one's digit. For the other digits N / 10.

Calculating Fibonacci Numbers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
that displays exactly 8 (eight) Fibonacci numbers starting and ending from user-specified numbers (program’s input). For example, if a user inputs index 3 and 10, then numbers (values) F3 - F10 are shown on the screen. Erroneous user’s input (e.g. negative number) or a smaller ending number than the first, should lead to warning and automatic repetition of the input.
To give you a small hint without doing all the work for you (as this seems to be some task for school, college, or university), here's how a Fibonacci number is defined:
f(0) = 0;
f(1) = 1;
f(n) = f(n - 1) + f(n - 2);
So in C++ this could be written like this:
int fibonacci(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
This of course can be further optimized and it's not necessarily the best approach. And it also includes possible errors, that might lead to stack overflows (hey, isn't that what this site is about? :)). So try to understand the code, then try to learn and improve it. Don't just copy & paste.

Separating number input into units [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I need to separate users input into units and store them in an array.
e.g if user enters 6547. Array will store {6,5,4,7} Using C++ on Linux
I would appreciate if you can help me with pseudocode or explain an algorithm.
I'm a beginner so please restrain from advising advanced function (and explain its use if you do) as we have studied basics so far
N.B| If such question has already been answered and I skipped it in search, please do point me to it.
The math for isolating right most digit:
digit = digit % 10;
The math for shifting a number right by one digit:
new_number = old_number / 10;
Every letter and number can be represented as a text character. For example, '5' is a character representing the single decimal digit 5.
The math for converting a textual digit (character) to numeric:
digit = char_digit - '0';
Example:
digit = '9' - '0';
The math for converting a numeric digit to a textual digit (character):
char_digit = digit + '0';
Example:
char_digit = 5 + '0';
Your problem basically breaks into few parts, which you need to figure out:
how to read one character from input
how to convert one character to the digit it represents
how to store it in the array
Please, try to explain if you have problem with some particular point from the list above or there is a problem somewhere else.
Suppose Variable input_string holds the number entered by the user & you want to store it in an array named 'a'...Here's a C snippet.. you can easily convert it into C++ code..
I would recommend taking the input as string rather than int so that you can directly insert the digits extracted from the end...(else you can start storing the integer from beginning and then reverse the array)
scanf("%s",&input_string)
size = strlen(input_string)-1
input = atoi(input_string)
while (input/10>0)
{
i=input%10;
input=input/10;
a[size]=i;
size--;
}
Hope that helps!
Here's a C++11 solution:
std::string input;
std::cin >> input;
int num = std::stoi(input);
std::vector<int> v_int;
for (unsigned int i = 0; i < input.size(); i++)
{
v_int.push_back(num % 10);
num /= 10;
}
// To get the numbers in the original order
std::sort(v_int.rbegin(), v_int.rend());
for (unsigned int i = 0; i < v_int.size(); i++) {
std::cout << v_int[i] << std::endl;
}
If you want it in a c-style array, do this:
int* dynamic_array = new int[v_int.size()];
std::copy(v_int.begin(), v_int.end(), dynamic_array);
delete dynamic_array;

Convert String Contents to Integers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I'm trying to convert the individual contents of a string to integers. I need to take each character from the string and convert it to an integer to add to another. This is not using C++11. Is there a simple way to do it?
if the characters are numbers then the numeral value of each is
num_value(c) = c - '0'
This is only possible because the characters representing numbers are in order in the ASCII table.. All you have to do is loop across the string.
"I need to take each character from the string and convert it to an integer to add to another"
In case you want to calculate the sum of digits stored in std::string object, you could do:
std::string myNum("567632");
int sum = 0;
for (size_t i = 0; i < myNum.size(); ++i)
sum += (myNum[i] - '0');
std::cout << sum;
which outputs 29 (i.e. 5 + 6 + 7 + 6 + 3 + 2)
How about std::accumulate ?
#include<string>
#include<algorithm>
//...
std::string myNum("123456789");
std::cout<<accumulate( myNum.begin(), myNum.end(), 0,
[](int sum,const char& x){return sum+=x-'0'; });