I am a beginner starting out in c++ and I am trying to turn a decimal byte into a binary number. However, there is something wrong with my syntax or logic but I cannot figure it out. When trying to debug, I believe the error is around userValue5 but I'm not sure why. Any tips are appreciated and I am using VS2015.
#include "stdafx.h"
#include <iostream>
#include <stdint.h>
#include <cmath>
//finds where each column is a 0 or a 1
int binaryDigit(uint16_t y, uint16_t power)
{
if ((y / (pow(2, power))) > 1)
return 1;
else
return 0;
}
int difference(uint16_t y, int x, uint16_t power)
{
if (x == 1)
return y - pow(2, power);
else
return y;
}
//takes a decimal byte and turns it into binary
int main()
{
using namespace std;
cout << "Please insert a number between 0 and 255 so that I can convert it to binary: ";
uint16_t userValue(0), power(7);
cin >> userValue;
int firstDigit = binaryDigit(userValue, power);
uint16_t userValue2 = difference(userValue, firstDigit, power);
--power;
int secondDigit = binaryDigit(userValue2, power);
uint16_t userValue3 = difference(userValue2, secondDigit, power);
--power;
int thirdDigit = binaryDigit(userValue3, power);
uint16_t userValue4 = difference(userValue3, thirdDigit, power);
--power;
int fourthDigit = binaryDigit(userValue4, power);
uint16_t userValue5 = difference(userValue4, thirdDigit, power);
--power;
int fifthDigit = binaryDigit(userValue5, power);
uint16_t userValue6 = difference(userValue5, thirdDigit, power);
--power;
int sixthDigit = binaryDigit(userValue6, power);
uint16_t userValue7 = difference(userValue6, thirdDigit, power);
--power;
int seventhDigit = binaryDigit(userValue7, power);
uint16_t userValue8 = difference(userValue7, thirdDigit, power);
--power;
int eigthDigit = binaryDigit(userValue8, power);
cout << "The number " << userValue << " in binary is ";
cout << firstDigit << secondDigit << thirdDigit << fourthDigit << " " << fifthDigit << sixthDigit << seventhDigit << eigthDigit << endl;
return 0;
}
bitset is your friend.
#include <bitset>
#include <iostream>
using namespace std;
int main()
{
int userValue = 0;
cout << "Please insert a number between " << INT_MIN << " and " << INT_MAX << " so that I can convert it to binary: ";
cin >> userValue;
cout << bitset<32>(userValue) << endl;
return 0;
}
However, if you want to convert it to a string, you'll probably need stringstream:
stringstream ss;
ss << bitset<32>(userValue);
string str = ss.str();
I figured it out. When I copied and pasted the same code to save time, I forgot to edit the arguments so that's why it wasn't working properly. I fixed it and it works great. Thank you to everyone who commented and posted things like the table of exponents and the bit masking. I've learned a lot and cannot wait to write more programs.
bitset is the way to go, but in general, maybe this is more helpful...
std::string intToBinaryString(int x)
{
// a useful class that allows easy concatenation
std::stringstream ss;
// create an integer that only has a 1 bit in its top position.
unsigned int mask = 1 << (sizeof(int) * 8 - 1);
// for each bit in x, starting at the top, check to see if its non zero...
for(int i = 0; i <sizeof(int) * 8; ++i)
{
// see if x's (top - i)'th bit is non zero
bool nonZeroBit = x & mask;
// assign the (top - i)'th "bit" of ss to be '1' if non zero and '0' otherwise
ss << (nonZeroBit ? '1' : '0');
// shift the mask down by 1.
mask >>= 1;
}
// What we get on the first iteration is
//
// mask = 10000...0000
// & x = 10101...0010
// -----------------------------
// nonZero = 10000...0000 = true
//
// the second iteration is
//
// mask = 01000...0000
// & x = 10101...0010
// -----------------------------
// nonZero = 00000...0000 = false
//
// the third iteration is
//
// mask = 00100...0000
// & x = 10101...0010
// -----------------------------
// nonZero = 00100...0000 = true
//
// ...
//
// then we just add these results into ss
// finally, convert it into a normal string
return ss.str();
}
Related
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
double* cal1(double* all1)
{
int t,count=0;
ifstream srcFile("in.txt", ios::in);
if (!srcFile)
{
cout << "error opening source file." << endl;
return 0;
}
char x;
while (srcFile >> x)
{
t = x - 'a' ;
count++;
if (t >= 0 && t <= 25)
all1[t]++;
else
all1[26]++;
}
all1[27] =count ;
srcFile.close();
/* for (t = 0; t <= 26; t++)
{
cout << all1[t] / all1[27]<<endl;
}
cout << all1[27] << endl;*/
return all1;
}
double finalcal1(double* all)
{
int t;
double p,cal1=0;
for (t = 0; t <= 26; t++)
{
p = (all[t] / all[27]);
all[t] = p * log(p);
}
for (t = 0; t <= 26; t++)
{
cal1 -= all[t];
}
return cal1;
}
int main()
{
double *all =new double[28]; //1
double t;
all = cal1(all);
t = finalcal1(all);
cout << t << endl;
delete[] all;
return 0;
}
enter code here
instead of receiving a number from the result, I just got a “-nan.(ind)” which is not even a number. Besides, when I change the number from mark 1 to *all =new double[27] which is what it supposed to be, there would be error or bugs showing up.
double *all =new double[28];
You probably want to initialise all these values to zero to start with since, otherwise, they'll have arbitrary values.
And, if those arbitrary values consist of any NaN items, that will propagate when you add things to them, or divide by some count.
Something like this will do the trick:
double *all = new double[28]();
You may also want to consider the possibility that log(x) is not actually defined for all values of x (such as zero or negative values) - that may be another way in which you could get a NaN.
this is my first time posting a question. I was hoping to get some help on a very old computer science assignment that I never got around to finishing. I'm no longer taking the class, just want to see how to solve this.
Read in an integer (any valid 64-bit
integer = long long type) and output the same number but with commas inserted.
If the user entered -1234567890, your program should output -1,234,567,890. Commas
should appear after every three significant digits (provided more digits remain) starting
from the decimal point and working left toward more significant digits. If the number
entered does not require commas, do not add any. For example, if the input is 234 you
should output 234. The input 0 should produce output 0. Note in the example above
that the number can be positive or negative. Your output must maintain the case of the
input.
I'm relatively new to programming, and this was all I could come up with:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long n;
cout << "Enter an integer:" << endl;
cin >> n;
int ones = n % 10;
int tens = n / 10 % 10;
int hund = n / 100 % 10;
int thous = n / 1000 % 10;
int tthous = n / 10000 % 10;
cout << tthous << thous << "," << hund << tens << ones << endl;
return 0;
}
The original assignment prohibited the use of strings, arrays, and vectors, so please refrain from giving suggestions/solutions that involve these.
I'm aware that some sort of for-loop would probably be required to properly insert the commas in the necessary places, but I just do not know how to go about implementing this.
Thank you in advance to anyone who offers their help!
Just to give you an idea how to solve this, I've maiden a simple implementation. Just keep in mind that is just a simple example:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long n = -1234567890;
if ( n < 0 )
cout << '-';
n = abs(n);
for (long long i = 1000000000000; i > 0; i /= 1000) {
if ( n / i <= 0 ) continue;
cout << n / i ;
n = n - ( n / i) * i;
if ( n > 0 )
cout << ',';
}
return 0;
}
http://coliru.stacked-crooked.com/a/150f75db89c46e99
The easy solution would be to use ios::imbue to set a locale that would do all the work for you:
std::cout.imbue(std::locale(""));
std::cout << n << std::endl;
However, if the restraints don't allow for strings or vectors I doubt that this would be a valid solution. Instead you could use recursion:
void print(long long n, int counter) {
if (n > 0) {
print(n / 10, ++counter);
if (counter % 3 == 0) {
std::cout << ",";
}
std::cout << n%10;
}
}
void print(long long n) {
if (n < 0) {
std::cout << "-";
n *= -1;
}
print(n, 0);
}
And then in the main simply call print(n);
A small template class comma_sep may be a solution, the usage may be as simple as:
cout << comma_sep<long long>(7497592752850).sep() << endl;
Which outputs:
7,497,592,752,850
Picked from here:
https://github.com/arloan/libimsux/blob/main/comma_sep.hxx
template <class I = int, int maxdigits = 32>
class comma_sep
char buff[maxdigits + maxdigits / 3 + 2];
char * p;
I i;
char sc;
public:
comma_sep(I i, char c = ',') : p(buff), i(i), sc(c) {
if (i < 0) {
buff[0] = '-';
*++p = '\0';
}
}
const char * sep() {
return _sep(std::abs(i));
}
private:
const char * _sep(I i) {
I r = i % 1000;
I n = i / 1000;
if (n > 0) {
_sep(n);
p += sprintf(p, "%c%03d", sc, (int)r);
*p = '\0';
} else {
p += sprintf(p, "%d", (int)r);
*p = '\0';
}
return buff;
}
};
The above class handles only integeral numbers, float/double numbers need to use a partial specialized version:
template<int maxd>
class comma_sep<double, maxd> {
comma_sep<int64_t, maxd> _cs;
char fs[64];
double f;
public:
const int max_frac = 12;
comma_sep(double d, char c = ',') : _cs((int64_t)d, c) {
double np;
f = std::abs(modf(d, &np));
}
const char * sep(int frac = 3) {
if (frac < 1 || frac > max_frac) {
throw std::invalid_argument("factional part too too long or invalid");
}
auto p = _cs.sep();
strcpy(fs, p);
char fmt[8], tmp[max_frac+3];
sprintf(fmt, "%%.%dlf", frac);
sprintf(tmp, fmt, f);
return strcat(fs, tmp + 1);
}
};
The two above classes can be improved by adding type-traits like std::is_integral and/or std::is_floating_point, though.
I have an uint32_t variable and I want to modify randombly the first 10 less significant bits(0-9) and then,still randomly, I want to modify bits from 10th to 23th. I wrote this simple program in C++ and it works for the first 10 bits but not for the others. I can't understand why
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <math.h>
using namespace std;
void printuint(uint32_t value);
int main(){
uint32_t initval=0xFFFFFFFF;
uint32_t address;
uint32_t value;
uint32_t final;
address=rand()%1024;
address<<=23;
printf("address \n");
printuint(address);
printf("final\n");
final = (initval & address);
printuint(final);
return 0;
}
void printuint (uint32_t value){
while (value) {
printf("%d", value & 1);
value >>= 1;
}
cout<<endl;
}
Adding this
value = rand() % 16384;
printuint(value);
and modifing final = (initval & address) & value;
Here's an example of flipping random bits:
int main(void)
{
srand(time());
unsigned int value = 0;
for (unsigned int iterations = 0;
iterations < 10;
++iterations)
{
unsigned int bit_position_to_change = rand() % sizeof(unsigned int);
unsigned int bit_value = 1 << bit_position_to_change;
value = value ^ bit_value; // flip the bit.
std::cout << "Iteration: " << iterations
<< ", value: 0x" << hex << value
<< "\n";
}
return EXIT_SUCCESS;
}
The exclusive-OR function, represented by operator ^, is good for flipping bits.
Another method is to replace bits:
unsigned int bit_pattern;
unsigned int bit_mask; // contains a 1 bit in each position to replace.
value = value & ~bit_mask; // Clear bits using the mask
value = value | bit_pattern; // Put new bit pattern in place.
Sorry I solved my problem with more patience.
What I meant to do is this:
uint32_t initval;
uint32_t address(1023);
bitset<32> bits(address);
cout << bits.to_string() << endl;
uint32_t value(16383);
value<<=10;
bitset<32> bitsvalue(value);
cout << bitsvalue.to_string() << endl;
initval = address | value;
bitset<32> bitsinit(initval);
cout << bitsinit.to_string() << endl;
return 0;
i am learning recursion in C++ and as practice i was trying to write binary to decimal converter with recursive function. In following code converter is working as it should:
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int sum = 0;
int DecimalConversion (int power, int number){
int bit;
if (number == 0)
{
return 0;
}
bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
DecimalConversion(power, number);
return sum;
//return bit * pow(2, power) + DecimalConversion(power, number);
}
int main(){
int power = 0;
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(power, number);
system("PAUSE >> NULL");
return 0;
}
Is it possible to return value from DecimalCoonversion function by not using global variable? Can someone explain how, I tried next line of code but it does not work correctly:
return bit * pow(2, power) + DecimalConversion(power, number);
Can anyone explain where i am making mistake using previous line of code?
Thank You in advance
This adds sum as a parameter to your function, but makes it default to 0 if you don't provide it explictly. Power is also defaulted to 0, which saves you having to pass it into the function.
Since default parameters must be at the end of a function declarations and/or definitions parameter list, I had to move power across to achieve this.
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int DecimalConversion (int number, int power = 0, int sum = 0) // changes here
{
if (number == 0)
{
return sum;
}
int bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
return DecimalConversion(number, power, sum); // changes here
}
int main(){
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(number);
system("PAUSE >> NULL");
return 0;
}
Please note I didn't check this actually converts binary to decimal correctly, just that the recursion works.
You can call this function like so:
DecimalConversion(number);
This:
int DecimalConversion(int power, int number){
if (number == 0)
return 0;
else
return (number % 10)*pow(2, power) + dc(power+1, number/10);
}
or
int DecimalConversion(int power, int number){
return number?(number % 10)*pow(2, power) + dc(power+1, number/10):0;
}
I have a IEEE754 Double precision 64-bit binary string representation of a double number.
example : double value = 0.999;
Its binary representation is "0011111111101111111101111100111011011001000101101000011100101011"
I want to convert this string back to a double number in c++.
I dont want to use any external libraries or .dll's as my program would operate in any platform.
C string solution:
#include <cstring> // needed for all three solutions because of memcpy
double bitstring_to_double(const char* p)
{
unsigned long long x = 0;
for (; *p; ++p)
{
x = (x << 1) + (*p - '0');
}
double d;
memcpy(&d, &x, 8);
return d;
}
std::string solution:
#include <string>
double bitstring_to_double(const std::string& s)
{
unsigned long long x = 0;
for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
{
x = (x << 1) + (*it - '0');
}
double d;
memcpy(&d, &x, 8);
return d;
}
generic solution:
template<typename InputIterator>
double bitstring_to_double(InputIterator begin, InputIterator end)
{
unsigned long long x = 0;
for (; begin != end; ++begin)
{
x = (x << 1) + (*begin - '0');
}
double d;
memcpy(&d, &x, 8);
return d;
}
example calls:
#include <iostream>
int main()
{
const char * p = "0011111111101111111101111100111011011001000101101000011100101011";
std::cout << bitstring_to_double(p) << '\n';
std::string s(p);
std::cout << bitstring_to_double(s) << '\n';
std::cout << bitstring_to_double(s.begin(), s.end()) << '\n';
std::cout << bitstring_to_double(p + 0, p + 64) << '\n';
}
Note: I assume unsigned long long has 64 bits. A cleaner solution would be to include <cstdint> and use uint64_t instead, assuming your compiler is up to date and provides that C++11 header.
A starting point would be to iterate through the individual characters in the string and set individual bits of an existing double.
Is it really a character string of binary bits? If so, first convert to a 64-bit int. Then either use a library routine (probably there is one somewhere), or more simply, use a double aliased over the 64-bit int to convert to double.
(If it's already a 64-bit int then skip the first step.)
Ignoring byte-ordering issues, but I suppose this should be a viable option:
The below has an outcome of .999 on i386 with gcc. See it live: https://ideone.com/i4ygJ
#include <cstdint>
#include <sstream>
#include <iostream>
#include <bitset>
int main()
{
std::istringstream iss("0011111111101111111101111100111011011001000101101000011100101011");
std::bitset<32> hi, lo;
if (iss >> hi >> lo)
{
struct { uint32_t lo, hi; } words = { lo.to_ulong(), hi.to_ulong() };
double converted = *reinterpret_cast<double*>(&words);
std::cout << hi << std::endl;
std::cout << lo << std::endl;
std::cout << converted << std::endl;
}
}
my program would operate in any platform
Included I assume those whose double format isn't IEEE. Something like this should work:
#include <math.h>
...
int const dbl_exponent_bits = 11;
int const dbl_exponent_offset = 1023;
int const dbl_significand_bits = 52;
bool negative = (*num++ == '1');
int exponent = 0;
for (int i = 0; i < dbl_exponent_bits; ++i, ++num) {
exponent = 2*exponent + (*num == '1' ? 1 : 0);
}
double significand = 1;
for (int i = 0; i < dbl_significand_bits; ++i, ++num) {
significand = 2*significand + (*num == '1' ? 1 : 0);
}
assert(*num == '\0');
double result = ldexp(significand, exponent-(dbl_exponent_offset+dbl_significand_bits));
if (negative)
result = -result;