Write integers to binary file in Big Endian or Little endian form C++ [duplicate] - c++

This question already has answers here:
How to check whether a system is big endian or little endian?
(18 answers)
How do I convert between big-endian and little-endian values in C++?
(35 answers)
Closed 5 months ago.
My teacher told me to:
Write the first M negative odd numbers in 16bit and little endian form
Write the first N positive even numbers in 32bit and big endian form
And this is my code thus far. I was able to do everything except for that endianess part
#include <iostream>
#include <fstream>
using namespace std;
int main() {
//writing to file section
int m, n;
ofstream bin("D://Ex02.bin", ios::binary | ios::out);
cin >> m >> n;
//Write the first M negative odd numbers in 16bit (2bytes)
for (int i = 0; i <= m; i++) {
int I = -2 * i - 1;
bin.write((char*)&I, 2);
}
//Write the first N positive even numbers in 32bit (4bytes)
for (int i = 0; i <= n; i++) {
int I = 2 * i;
bin.write((char*)&I, 4);
}
bin.close();
//test section
ifstream test("D://Ex02.bin", ios::binary | ios::in);
//Read 16 bit numbers
int x = -pow(2,16) + 1;
for (int i = 0; i <= m; i++) {
test.read((char*)&x, 2);
cout << x << endl;
}
//Read 32 bit numbers
x = 0;
for (int i = 0; i <= n; i++) {
test.read((char*)&x, 4);
cout << x << endl;
}
test.close();
return 0;
}
The problem is that I have no idea how to write integer in specific endian form.
Can someone help me pls

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).

Fraction pattern in c++ [duplicate]

This question already has answers here:
C++. Dividing 1 by any number gives 0
(3 answers)
Closed 1 year ago.
I need to write a program to run this pattern in c++:
S=1/2+2/3+3/4+4/5+...+N-1/N
I have tried but my code is showing 0.
And its the code that I have written:
#include <iostream>
using namespace std;
int main()
{
unsigned int N;
float S=0;
cout << "Enter N:";
cin >> N;
for (int I = 2; I <= N; I++)
{
S = S + (I - 1) / I;
}
cout << S;
return 0;
}
I have to write it with for-loop, while and do-while
(I - 1) / I only contains integers, therefore any remainder is discarded.
You can avoid this by simply subtracting - 1.f off of I instead.

How do I convert a number into an 8-bit binary rather than 4-bit

void decimaltobin()
{
binaryNum = 0;
m = 1;
while (num != 0)
{
rem = num % 2;
num /= 2;
binaryNum += rem * m;
m *= 10;
}
}
Just wondering if there was an easy fix to get this function to print an 8-bit binary number instead of a 4-bit number, e.g. 0000 0101 instead of 0101.
As mentioned in the comments, your code does not print anything yet and the data type of binaryNum is not clear. Here is a working solution.
#include <iostream>
using namespace std;
void decToBinary(int n)
{
// array to store binary number
int binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing the required number of zeros
int zeros = 8 - i;
for(int m = 0; m < zeros; m++){
cout<<0;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
// Driver program to test above function
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
The code implements the following:
Store the remainder when the number is divided by 2 in an array.
Divide the number by 2
Repeat the above two steps until the number is greater than zero.
Print the required number of zeros. That is 8 - length of the binary number. Note that this code will work for numbers that can be expressed in 8 bits only.
Print the array in reverse order now
Ref
Maybe I am missing your reason but why do you want to code from scratch instead of using a standard library?
You may use standard c++ without having to code a conversion from scratch using for instance std::bitset<NB_OF_BITS>.
Here is a simple example:
#include <iostream>
#include <bitset>
std::bitset<8> decimalToBin(int numberToConvert)
{
return std::bitset<8>(numberToConvert);
}
int main() {
int a = 4, b=8, c=12;
std::cout << decimalToBin(a)<< std::endl;
std::cout << decimalToBin(b)<< std::endl;
std::cout << decimalToBin(c)<< std::endl;
}
It outputs:
00000100
00001000
00001100

Convert number in binary and print out as matrix (C++)

Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific.
I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0's in the number as H. Afterwards it will print out the results (the binary number with the H and T replacement) as a 3*3 matrix.
This is the desired output (not what I have but what I want):
Enter a number between 0 and 511: 299
The binary number is: 100101011
The matrix is:
THH
THT
HTT
The problem with my code is that I am unsure of how to replace an array that consists of all integers to have certain parts of the index to be either characters or strings. For sure the part with the binary number conversion works but the replacement of the 0's and 1's of the array is where the trouble is at. I am also unsure of how to print out the matrix result. I assume it goes either of 2 ways: 1. The program creates a new array for the previous array's elements stored and prints out the matrix array instead. 2. There is a way to only print the array 3 lines at a time. The only way I can think of is to somehow cut the for loop short and add a line break after every 3 values. I am aware that there are a few pointable errors in my code but I do not know how to fix them.
Although this is in the C++ language, what I have learned is the C style syntax (no std:: kinds of code or stuff like that because I haven't learned it yet and I will not understand it) So far I have learned basic arrays, loops, and functions.
#include <iostream>
using namespace std;
int main(){
int arr[10];
int input, i;
cout<<"Enter a number between 0 and 511: ";
cin>> input;
for(i = 0; input > 0; i++){
arr[i] = (input % 2);
input = input / 2;
}
cout<<"The binary number is: ";
for(i = i - 1; i >= 0; i--){
cout<<arr[i];
}
string newArr[10] = arr[10]; //the error here states that the array initializer must be an initializer list
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
if(arr[i] == 1){
arr[i] = "T"; //the error here mentions that a string/ character cannot be assigned with a integer array
}
else{
arr[i] = "H";
}
}
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
cout<<arr[i]<< " ";
}
}
This would be sufficient:
#include <iostream>
using namespace std;
int main()
{
// you never actually checked if the input is valid
// so you may or may not want this loop:
int input;
do
{
cout << "Enter a number between 0 and 511: ";
cin >> input;
} while ((input < 0) || (input > 511));
// space for matrix, new lines and null
// to construct a null terminated string
char buffer[3 * (3 + 1) + 1];
int i = 0;
// since the bits are read from left to right
// I will use a mask instead of bit shifting the input
int bit = 1 << 9;// 2^9 == 512
for (int r = 0; r < 3; r++)// rows
{
for (int c = 0; c < 3; c++)// columns
{
// this could come after the check
// and then bit would start at 256
bit >>= 1;
// perform the check and add the corresponding letter
buffer[i++] = (bit & input) ? 'T' : 'H';
}
// add new lines
buffer[i++] = '\n';
}
// if you don't want the last '\n'
// this could be { buffer[--i] = '\0'; }
buffer[i++] = '\0';
cout << buffer;
}

Using char for small integer value instead of using INT [duplicate]

This question already has answers here:
Standard Input for Unsigned Character
(2 answers)
Closed 6 years ago.
I am working on some codes using c++.
Type char is one byte in my machine and int type is four bytes.
Since my input value is under 100, I used char type instead of integer type in order to make my process in an efficient way as shown in below codes.
int do_main(int argc, const char *argv[]) {
int TC;
cin >> TC;
while (TC--) {
unsigned char num;
char code[7];
for (int i = 0; i < 7; ++i) code[i] = 0;
cin >> num;
int idx = 0;
while (1) {
code[7-1-idx++] = num % 2;
num /= 2;
if (num < 2) break;
}
code[7 - 1 - idx] = num;
for (int i = 0; i < 7; ++i) cout << code[i] << endl;
}
return 0;
}
As you can see above codes, the 10 digit value is transformed into 2 bit type. However, my problem is that the value was not what I expected. it showed some strange character not 1 or zero.
I thought that it was due to the types. Therefore I modified the char into int and ran the codes again. I confirmed that the codes[i] showed the corrected value that I expected.
To summary.. my question is that what is wrong with the usage of char instead of int?
I know that char is aimed at storage of character but for some small integer value (up to 1 byte), we can use char instead of int type.
It is because std::cout's operator<<(char) is overloaded such that it will display ascii character corresponding to the digit. Instead of changing type from char to int, you can do like this
for (int i = 0; i < 7; ++i)
cout << static_cast<int>(code[i]) << endl;
See this.