c++ Algorithm to convert an integer into an array of bool - c++

I'm trying to code an algorithm that will save to file as binary strings every integer in a range. Eg, for the range 0 to 7:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Note that the leading zeros and spaces between digits are essential.
What I cant figure out how to do in a simple way is to convert the integers to binary numbers represented by bool []s (or some alternate approach).
EDIT
As requested, my solution so far is:
const int NUM_INPUTS = 6;
bool digits[NUM_INPUTS] = {0};
int NUM_PATTERNS = pow(2, NUM_INPUTS);
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1 ; w--)
{
if( ! ((q+1) % ( (int) pow(2, w))) )
digits[w] = !digits[w];
outf << digits[w] << " ";
}
outf << "\n";
}
Unfortunately, this is a bit screwy as the first pattern it gives me is 000001 instead of 000000.
This is not homework. I'm just coding a simple algorithm to give me an input file for training a neural network.

Don't use pow. Just use binary math:
const int NUM_INPUTS = 6;
int NUM_PATTERNS = 1 << NUM_INPUTS;
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1; w--)
{
outf << ((q>>w) & 1) << " ";
}
outf << "\n";
}

Note: I'm not providing code, but merely a hint because the question sounds like homework
This is quite easy. See this example:
number = 23
binary representation = 10111
first digit = (number )&1 = 1
second digit = (number>>1)&1 = 1
third digit = (number>>2)&1 = 1
fourth digit = (number>>3)&1 = 1
fifth digit = (number>>4)&1 = 1
Alternatively written:
temp = number
for i from 0 to digits_count
digit i = temp&1
temp >>= 1
Note that the order of digits taken by this algorithm is the reverse of what you want to print.

The lazy way would be to use std::bitset.
Example:
#include <bitset>
#include <iostream>
int main()
{
for (unsigned int i = 0; i != 8; ++i){
std::bitset<3> b(i);
std::cout << b << std::endl;
}
}
If you want to output the bits individually, space-separated, replace std::cout << b << std::endl; with a call to something like Write(b), with Write defined as:
template<std::size_t S>
void Write(const std::bitset<S>& B)
{
for (int i = S - 1; i >= 0; --i){
std::cout << std::noboolalpha << B[i] << " ";
}
std::cout << std::endl;
}

Related

Converting an array of decimals to 8-bit binary form in c++

Okay so I'm tryna create a program that:
(1) swaps my array
(2) performs caesar cipher substitution on the swapped array
(3) convert the array from (2) that is in decimal form into 8-bit binary form
And so far I've successfully done the first 2 parts but I'm facing problem with converting the array from decimal to binary form.
And this is my coding of what I've tried
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void swapfrontback(int a[], int n);
int main()
{
int a[10], i, n;
cout << "enter size" << endl;
cin >> n;
if (n == 0)
{
cout << "Array is empty!\n";
}
else
{
cout << "p = " << endl;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
}
swapfrontback(a,n);
//caesar cipher
int shift = 0;
cout << "input shift: ";
cin >> shift;
int modulus = 0;
cout << "input modulus: ";
cin >> modulus;
cout << "p''=" << endl;
for (i = 0; i < n; i++)
{
a[i] = (a[i] + shift) % modulus;
cout << a[i] << endl;
}
// Function that convert Decimal to binary
int b;
b = 8;
cout<< "p'''=" << endl;
for (i = 0; i < n; i++)
{
for(int i=b-1;i>=0;i--)
{
if( a[i] & ( 1 << i ) ) cout<<1;
else cout<<0;
}
}
return 0;
}
void swapfrontback(int a[], int n)
{
int i, temp;
for (i = 0; i < n / 2; i++)
{
temp = a[i];
a[i] = a[n - i-1];
a[n - i-1] = temp;
}
cout << "p' = '" << endl;
for (i = 0; i < n; i++)
{
cout << a[i] << endl;
}
}
the problem is that instead of converting the array of decimal from the 2nd part which is the caesar cipher into its binary form, I'm getting 000000010000000100000001 .
My initial array is
3
18
25
Shift 8 and modulo 26. If anyone knows how to fix this please do help me.
Well, there seems to be something that may be an issue in the future (like the n being larger than 10, but, regarding your question, this nested for sentence is wrong.
for (i = 0; i < n; i++)
{
for(int i=b-1;i>=0;i--) //here you are using the variable 'i' twice
{
if( a[i] & ( 1 << i ) ) cout<<1; //i starts at 7, which binary representation in 4 bits is 0111
else cout<<0;
}
}
When you're using nested for sentences, it is a good idea to not repeat their iterating variables' names since they can affect each other and create nasty things like infinite loops or something like that. Try to use a different variable name instead to avoid confusion and issues:
for(int j=b-1;j>=0;j--) //this is an example
Finally, the idea behind transforming a base 10 number to its binary representation (is to use the & operator with the number 1 to know if a given bit position is a 1 (true) or 0 (false)) for example, imagine that you want to convert 14 to its binary form (00001110), the idea is to start making the & operation with the number 1, an continue with powers of 2 (since them will always be a number with a single 1 and trailing 0s) 1-1 2-10 4-100 8-1000, etc.
So you start with j = 1 and you apply the & operation between it and your number (14 in this case) so: 00000001 & 00001110 is 0 because there is not a given index in which both numbers have a '1' bit in common, so the first bit of 14 is 0, then you either multiply j by two (j*=2), or shift their bits to the left once (j = 1<<j) to move your bit one position to the left, now j = 2 (00000010), and 2 & 14 is 2 because they both have the second bit at '1', so, since the result is not 0, we know that the second bit of 14 is '1', the algorithm is something like:
int j = 128; 128 because this is the number with a '1' in the 8th bit (your 8 bit limit)
int mynumber = 14;
while(j){ // when the j value is 0, it will be the same as false
if(mynumber & j) cout<<1;
else cout<<0;
j=j>>1;
}
Hope you understand, please ensure that your numbers fit in 8 bits (255 max).

How to convert an integer to an array of its digits in C++

Suppose I have the integer 1004.
I want to store this in the array A with the following pattern:
A[0]=1
A[1]=0
A[2]=0
A[3]=4
How can I get the value at that index ?
How can I do this in C++?
You get the last index of a number by using modulo 10 and then remove that value by dividing the number by 10.
So assume you do this:
1004 % 10 = 4
1004 / 10 = 100
Then repeat that for each digit
Using c++ static memory:
int originalNumber = 1004;
int digitArray[10] = {0};
int idx = 0;
while (originalNumber > 0)
{
int digit = n % 10;
originalNumber /= 10;
digitArray[idx] = digit;
++idx;
}
// Reverse the order of the array
std::reverse(std::begin(digitArray), std::begin(digitArray)+(idx-1));
I'm not sure if it's the most efficient way of doing this but it definitely works.
You can enter each digit in the number to the array but from the end of the array to the beginning.
For example, there is an array with the size of 4, so you get the last digit of the number like this: num % 10, and push the digit to the third index of the array.
Code example:
#define SIZE 4
int* numToArray(int num)
{
int* arr = new int[SIZE]; // assuming you already know the number of digits in the number
for(int i = SIZE-1; i >= 0; i++)
{
arr[i] = num % 10; // Enters the last digit to the array
num /= 10; // Gets rid of the last digit in the number
}
return arr;
}
Instead of ordinary integer array, I suggest you using std::vector instead.
Then, you can have something like the following:
#include <iostream>
#include <vector>
int main() {
int number = 1004;
std::vector<int> digits;
while (number != 0) {
digits.insert(digits.begin(), number % 10);
number /= 10;
}
for (auto const i : digits) {
std::cout << i << " "; // 1 0 0 4
}
// or by index
std::cout << std::endl;
std::cout << "[0]" << digits[0] << std::endl; // 1
std::cout << "[1]" << digits[1] << std::endl; // 0
std::cout << "[2]" << digits[2] << std::endl; // 0
std::cout << "[3]" << digits[3] << std::endl; // 4
return 0;
}
Demo
Adding to all the existing answers I'd like to propose a more elegant, if probably less efficient approach utilizing the many wonders of the standard library.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
auto number = 1004;
auto asString = std::to_string(number); //
std::vector<int> digits(asString.length());
std::transform(asString.begin(), asString.end(), digits.begin(), [](char c){return c -'0';});
for(auto d : digits)
{
std::cout << d << ' ';
}
}

Pattern Printing-Where am I going wrong in this C++ code?

I wrote a program to print a N x N square pattern with alternate 0's and 1's. For eg. A 5 x 5 square would looks like this:
I used the following code-
#include<iostream.h>
int main()
{
int i, n;
cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
cout << " " << i%2;
if(i%n == 0)
cout << "\n";
}
fflush(stdin);
getchar();
return 0;
}
This code works fine for odd numbers but for even numbers it prints the same thing in each new line and not alternate pattern.For 4 it prints this-
Where am I going wrong?
In my opinion the best way to iterate over matrix is using loop in another loop.
I think this code will be helpful for you:
for(i = 0; i < n; i++) {
for (j = 1; j <= n; j++) {
cout<<" "<< (j + i) % 2;
}
cout<<"\n";
}
where n is number of rows, i and j are ints.
Try to understand why and how it works.
If you're a beginner programmer, then I suggest (no offence) not trying to be too clever with your methodology; the main reason why your code is not working is (apart from various syntax errors) a logic error - as pointed out by blauerschluessel.
Just use two loops, one for rows and one for columns:
for (int row = 1; row <= n; row++)
{
for (int col = 0; col < n; col++)
cout << " " << ((row % 2) ^ (col % 2));
cout << "\n";
}
EDIT: since you wanted a one-loop solution, a good way to do so would be to set a flip flag which handles the difference between even and odd n:
bool flip = false;
int nsq = n * n;
for (int i = 1; i <= nsq; i++)
{
cout << " " << (flip ^ (i % 2));
if (i % n == 0) {
if (n % 2 == 0) flip = !flip;
cout << "\n";
}
}
The reason that it isn't working and creating is because of your logic. To fix this you need to change what the code does. The easiest way to handle that is to think of what it does and compare that to what you want it to do. This sounds like it is for an assignment so we could give you the answer but then you would get nothing from our help so I've writen this answer to guide you to the logic of solving it yourself.
Lets start with what it does.
Currently it is going to print 0 or 1 n*n times. You have a counter named i that will increment every time starting from 0 and going to (n*n)-1. If you were to print this number i you would get the following table for n=5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Now you currently check if the value i is odd or even i%2 and this makes the value 0 or 1. Giving you the following table
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
Now in the case of n=4 your counter i would print out to give you a table
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now if you print out the odd or even pattern you get
1 0 1 0
1 0 1 0
1 0 1 0
1 0 1 0
This pattern diffrence is because of the changing pattern of printed numbers due to the shape of the square or more accurately matrix you are printing. To fix this you need to adjust the logic of how you determine which number to print because it will only work for matrixes that have odd widths.
You just need to add one more parameter to print the value. Below mentioned code has the updated for loop which you are using:
int num = 0;
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
The complete compiled code :
#include <iostream>
#include <stdio.h>
int main()
{
int i, n, num = 0;
std::cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
fflush(stdin);
getchar();
return 0;
}

Are i < N+1 and i <= N different?

I used to know that There is no difference between i <= N and i < N+1
However, when I enter 6 6 to program.
if i <= N then it print
1 6 6 6 1 1 2 3 3 3 2 2
otherwise
1 6 6 6 1 1 2 3 3 3 2 2 3 2 2 2 3 3
I can't figure out why it make a difference
#include <iostream>
#include <cmath>
using namespace std;
typedef long long LNT;
LNT gcd(LNT a, LNT b)
{
if( b == 0)
return a;
return gcd(b, a%b);
}
int main()
{
LNT red, green;
LNT GCD;
cin >> red >> green;
GCD = gcd(red, green);
//for(LNT i = 1; i<sqrtl(GCD)+1; i++)
for(LNT i = 1; i<=sqrtl(GCD); i++) // <- This Line cause the difference
{
if( GCD % i == 0)
{
cout << i << " " << red/i << " " << green/i <<endl;
if( i != GCD/i )
{
LNT k = GCD/i;
cout << k << " " << red/k << " " << green/k <<endl;
}
}
}
}
This is true only for integer values. As sqrtl returns long double, in case it's fractional then for the fraction it will still differ if you compare original with fraction and +1 where one another integer fits:
! 2 <= 1.5
2 < 1.5+1
sqrtl return long double in this case your assumption:
no difference between i <= N and i < N+1
is wrong.
well,there is no difference between i<=n and i < n+1 as both of them runs till only n but what u doing is sqrt which returns long double and for them not necessarily to be same.

Is this an inefficent way to convert from a binary string to decimal value?

while(i < length)
{
pow = 1;
for(int j = 0; j < 8; j++, pow *=2)
{
ch += (str[j] - 48) * pow;
}
str = str.substr(8);
i+=8;
cout << ch;
ch = 0;
}
This seems to be slowing my program down a lot. Is it because of the string functions I'm using in there, or is this approach wrong in general. I know there's the way where you implement long division, but I wanted to see if that was actually more efficient than this method. I can't think of another way that doesn't use the same general algorithm, so maybe it's just my implementation that is the problem.
Perhaps you want might to look into using the standard library functions. They're probably at least as optimised as anything you run through the compiler:
#include <iostream>
#include <iomanip>
#include <cstdlib>
int main (void) {
const char *str = "10100101";
// Use str.c_str() if it's a real C++ string.
long int li = std::strtol (str, 0, 2);
std::cout
<< "binary string = " << str
<< ", decimal = " << li
<< ", hex = " << std::setbase (16) << li
<< '\n';
return 0;
}
The output is:
binary string = 10100101, decimal = 165, hex = a5
You are doing some things unnecessarily, like creating a new substring for each each loop. You could just use str[i + j] instead.
It is also not necessary to multiply 0 or 1 with the power. Just use an if-statement.
while(i < length)
{
pow = 1;
for(int j = 0; j < 8; j++, pow *=2)
{
if (str[i + j] == '1')
ch += pow;
}
i+=8;
cout << ch;
ch = 0;
}
This will at least run a bit faster.
short answer could be:
long int x = strtol(your_binary_c++_string.c_str(),(char **)NULL,2)
Probably you can use int or long int like below:
Just traverse the binary number step by step, starting from 0 to n-1, where n is the most significant bit(MSB) ,
multiply them with 2 with raising powers and add the sum together. E.g to convert 1000(which is binary equivalent of 8), just do the following
1 0 0 0 ==> going from right to left
0 x 2^0 = 0
0 x 2^1 = 0;
0 x 2^2 = 0;
1 x 2^3 = 8;
now add them together i.e 0+0+0+8 = 8; this the decimal equivalent of 1000. Please read the program below to have a better understanding how the concept
work. Note : The program works only for 16-bit binary numbers(non-floating) or less. Leave a comment if anything is not clear. You are bound to receive a reply.
// Program to convert binary to its decimal equivalent
#include <iostream>
#include <math.h>
int main()
{
int x;
int i=0,sum = 0;
// prompts the user to input a 16-bit binary number
std::cout<<" Enter the binary number (16-bit) : ";
std::cin>>x;
while ( i != 16 ) // runs 16 times
{
sum += (x%10) * pow(2,i);
x = x/10;
i++;
}
std::cout<<"\n The decimal equivalent is : "<<sum;
return 0;
}
How about something like:
int binstring_to_int(const std::string &str)
{
// 16 bits are 16 characters, but -1 since bits are numbered 0 to 15
std::string::size_type bitnum = str.length() - 1;
int value = 0;
for (auto ch : str)
{
value |= (ch == '1') << bitnum--;
}
return value;
}
It's the simplest I can think of. Note that this uses the new C++11 for-each loop construct, if your compiler can't handle it you can use
for (std::string::const_iterator i = str.begin(); i != str.end(); i++)
{
char ch = *i;
// ...
}
Minimize the number of operations and don't compute things more than once. Just multiply and move up:
unsigned int result = 0;
for (char * p = str; *p != 0; ++p)
{
result *= 2;
result += (*p - '0'); // this is either 0 or 1
}
The scheme is readily generalized to any base < 10.