I designed a C++ code for checking machine's endian.
It works well. But, it cannot print out each bytes' contents in a 4-byte int.
#include<iostream>
using namespace std;
bool f()
{
int a = 1;
char *p = (char*)&a;
for (int i = 0 ; i < 4 ; ++i)
cout << "p[" << i << "] is " << hex << *p++ << " ";
cout << endl ;
p -= 4;
if (*p == 1) return true ; // it is little endian
else return false; // it is big endian
}
int main()
{
cout << "it is little endian ? " << f() << endl ;
return 0 ;
}
output:
p[0] is p[1] is p[2] is p[3] is
it is little endian ? 1
Why the output is empty ?
thanks
the issue is that the type of *p is char, so the stream attempts to print the value of it as an ASCII character (which is likely not the value of a visible character). If you cast it to an int you will get what you expect:
cout << "p[" << i << "] is " << hex << static_cast<int>(*p++) << " ";
printf suggested is OK but also an alternative is using shift operators <<,>> to investigate individual bytes of the int.
I coded the following to print every byte of an int array. Each int was 4 bytes long.
Hope this helps in some way.
#include <iostream>
#include<math.h>
#include<string.h>
using namespace std;
int main()
{
int length = 5;
unsigned int* array = new unsigned int[length];
for(int i=0; i<length; i++)
array[i] = 16843009;
for(int i=0;i<=4;i++)
{
int new_dividend=0,k=0,l=0;
double bytevalue=0;
int bits[32];
int number=array[i];
//Initializing
for(int c=0;c<=31;c++)
{
bits[c]=0;
}
//convert to binary
while(number!=1)
{
new_dividend=number/2;
bits[k]=number%2;
number=new_dividend;
k++;
}
bits[k]=1;
//Pad with zero if needed
if(k!=31)
{
for(int ctr=k+1;ctr<=31;ctr++)
{
bits[ctr]=0;
}
}
for(int counter=0;counter<=31;counter++)
{
//Print value of each byte.Also Reset values after each bytevalue has been printed.
if(l==8)
{
l=0;
cout<<bytevalue;
bytevalue=0;
}
//calculate value of each byte
bytevalue=bytevalue+(pow(double(2),l))*bits[counter];
++l;
}
if(l==8)
{cout<<bytevalue;
}
}
delete[] array;
return 0;
}
Expected Output = 11111111111111111111 for an array[i] = 16843009 where i may be any range.
Related
int grades[100];
int j = 0;
int len = sizeof(grades)/sizeof(grades[0]);
while (j < len)
{
cout << grades[j] << endl;
j++;
}
I have entered only 5 grades and I want to print only that entered grades then ho can I print that?
I have tried to use length of array but since I have created array of size 100, it is printing all unwanted characters at the end.
I have also used '\0' to get end of array but it is not working.
#include <vector>
std::vector<int> grades;
// add 3 grades
grades.push_back(4);
grades.push_back(1);
grades.push_back(9);
// https://www.cplusplus.com/reference/vector/vector/size/
auto size = grades.size();
Just keep track of the size when you read the numbers:
#include <iostream>
int main()
{
int const max_len = 100;
int arr[max_len];
std::cout << "Enter numbers: ";
int len = 0;
while (len < max_len && std::cin >> arr[len]) {
++len;
}
// you've read `len` numbers.
std::cout << "You've entered " << len << " numbers\n";
for (int i = 0; i != len; ++i) {
std::cout << arr[i] << '\n';
}
}
Your code returns the total number of elements the array can store.
Try this instead:-
#include <iostream>
int main()
{
int sample[10];
int length = 0;
for (int integer : sample)
{
if (integer != NULL)
{
length++;
// If you want to print the element as well -
std::cout << integer << std::endl;
}
}
}
Essentially what it does goes through all of the elements of the array and adds 1 to length if that element is not NULL (NULL means a null pointer, or if you're a beginner, just know it means basically nothing).
You can easily change int to any other type.
Hope it helps :)
Why does the two arrays act differently in this case?
#include <bits/stdc++.h>
using namespace std;
int main() {
char a[100] = {}; // all white spaces
int b[100] = {} ; // all 0
for(int i = 0; i < 100; i++)
cout << a[i] << "\n";
for(int i = 0; i < 100; i++)
cout << b[i] << "\n";
}
It is indeed initialized to zeroes. Since it's a character array, zeros are just the \0 character. Change that line from
cout << a[i] << "\n";
to
std::cout << '[' <<a[i] <<']' <<std::boolalpha<< (a[i] == '\0') << "\n";
help confirm what you expect is true.
char a[100] = {}; // all white spaces
This line will initiate all elements to integer value 0, which when converted to it's ASCII equivalent is a null character.
...C++.....................
#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++){
cout << troysArray[i] << endl;
cout << troysArray[j] << endl;
};
return 0;
}
.......................
C++
Why does the above code print out hex numbers when I'm actually trying to print out the contents of the array. (Beginner/Just practicing)
What am I doing wrong that's causing this to occur?
The best overload of the std::ostream << operator for troysArray[i] is void* (exploiting pointer decay), and that outputs the address of the pointer.
If you want an element use troysArray[i][j] &c.
troysArray[i] and troysArray[j] are pointers to an array. If you want to print element at i and j, use
cout << troysArray[i][j] << endl;
troysArray is an array of arrays of int.
Thus, troysArray[i] is an array of int, and so is troysArray[j].
There is no overload of operator << for array of int.
However, there is one for void*.
When you pass an array as an argument, what actually gets passed is a pointer to the array's first element.
(In your case, those are &troysArray[i][0] and &troysArray[j][0], both of type int*.)
An int* can be implicitly converted to void*, so the operator << for void* can be used.
This overload outputs the value of the pointer in hexadecimal form.
In order to print the ints you need to print the elements j of each array troysArray[i]:
cout << troysArray[i][j] << endl;
To print it more "matrix-like", with each row on its own line:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << troysArray[i][j] << ' ';
}
cout << endl;
}
To print out the contents of the table in a grid (as asked in one of the comments on Guarev Senghai's answer:
#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
{
for (j = 0;j < 3;j++)
{
cout << troysArray[i][j];
//uncomment the next line to have a spaces between the numbers.
cout << " ";
}
cout << endl;
}
return 0;
}
This is a c++ program to convert decimal number to binary number. Well there are many possible ways to implement this but as I learned about the static variable I thought to make a use of it. So the program is
#include <iostream>
using namespace std;
int **binary(int num, int &k) {
static int *p;
int i = 0;
while (num > 0) {
*p = num % 2;
p++;
num = num / 2;
k++;
}
return &p;
}
int main() {
int n;
int k = 0;
cout << "\n Enter the number to be converted into binary : ";
cin >> n;
int **ptr;
ptr = binary(n, k);
cout << "\n The number of bytes in the binary number is : " << k << endl;
cout << "\n The binary code is : \n";
for (int i = 0; i < k; i++)
cout << **(ptr+i);
return 0;
}
Output:
Enter the number to be converted into binary : 33
Segmentation fault
After debugging this code I'm getting seg fault at line 9:9
i.e
*p = num % 2;
I don't know why this is leading me to access an unoccupied memory space in the stack.
The reason there is a crash is that p is initialized to nullptr. Dereferencing an uninitialized variable is undefined behavior, hence you get the crash.
Disclaimer: The following code is intended to fix your code. It is not intended to illustrate a proper way of doing this, or show a good way to code in general.
If you wish to play with function-static variables, and your function must return a pointer to pointer, initialize p by pointing it to another static variable which provides you with a buffer:
static int pVal[100];
static int * p;
p = pVal; // This should be done in an assignment, not in initializer
Note: Returning pointers to static storage makes your code non-reentrant, which is generally a very bad practice. This code is fine as a learning exercise, but it's not something one should use in production code.
static int * p; is never set. It is initialized to NULL, dereferencing it invokes undefined behavior. Using a static buffer is not recommended, it is better to pass an array to the function and return the number of bits. Furthermore, you should output these bits in the reverse order.
Since you are interested in static local variables, here is a corrected version of your code:
#include <iostream>
using namespace std;
int *binary(int num, int &k) {
static int bits[sizeof(int) * 8];
int *p = bits;
k = 0;
while (num > 0) {
*p = num % 2;
p++;
num = num / 2;
k++;
}
return p;
}
int main() {
int n;
int k = 0;
cout << "\n Enter the number to be converted into binary : ";
cin >> n;
int *ptr = binary(n, k);
cout << "\n The number of bits in the binary number is : " << k << endl;
cout << "\n The binary code is : \n";
for (int i = 0; i < k; i++)
cout << ptr[k - i];
return 0;
}
Here is a version that does not use a static buffer:
#include <iostream>
using namespace std;
int binary(unsigned int num, int *dest) {
for (int i = 0;;) {
dest[i++] = num & 1;
if ((num >>= 1) == 0)
return i;
}
}
int main() {
unsigned n;
int bits[sizeof(n) * 8];
cout << "\nEnter the number to be converted into binary: ";
cin >> n;
int k = binary(n, bits);
cout << "\nThe number of bits in the binary number is: " << k << endl;
cout << "\nThe binary code is: ";
for (int i = k; i-- > 0;)
cout << bits[i];
cout << endl;
return 0;
}
The code has numerous problems:
binary() does not initialise the pointer p to anything.
binary() dereferences the initialised p and modifies the value.
The conversion writes from LSB to MSB and the outputs writes in that order too.
You need to allocate a buffer to receive the conversion. This is safest done by the caller. Since ultimately you output the characters 1 or 0, your conversion may as well write those character values directly to a string.
I am writing a program where the input data (in binary) is split into half and convert to integer to perform some calculation.
So I:
Accept binary input and store as "String"
Split string (note: to be treated as binary) into half and convert to int and store in x and y
So far i have written step 1.
int main() {
string input;
cout << "Enter data:";
getline(cin, input);
int n = input.size();
int n1 = n/2;
string a, b;
a = input.substr(0,n1);
b = input.substr(n1);
cout << "a: " << a;
cout << "b: " << b;
}
Would like to know how to achieve step 2.
Thanks in advance.
You can try this:
if(a.length() <= sizeof(unsigned int) * 8) {
unsigned x = 0;
for(int i = 0; i < a.length(); i++) {
x <<= 1; // shift byt 1 to the right
if(a[i] == '1')
x |= 1; // set the bit
else if(a[i] != '0') {
cout << "Attention: Invalid input: " << a[i] << endl;
break;
}
}
cout << "Result is " << x << endl;
}
else cout << "Input too long for an int" << endl;
It uses
shift left <<, to move the binary bits, when you go right in the ascii string;
binary or | for setting the bits.
int bin2dec(char* str) {
int n = 0;
int size = strlen(str) - 1;
int count = 0;
while ( *str != '\0' ) {
if ( *str == '1' )
n = n + pow(2, size - count );
count++;
str++;
}
return n;
}
int main() {
char* bin_str = "1100100";
cout << bin2dec(bin_str) << endl;
}