Inspiring from a obfuscated piece of code, I have a small question regarding to assign value to an integer:
#include <iostream>
#include <cstdio>
int main() {
int i = 0101;
std::cout << i << "\n";
}
And the output was 65, and I have no idea where 65 came from? Any idea?
It specifies an octal (base-8) number: 0101 == 1 * (8 * 8) + 1 == 65.
Lambert already explained that. So let me tell you what else you can do.
You can write hexadecimal integer:
int main() {
int i = 0x101; //0x specifies this (i.e 101) is hexadecimal integer
std::cout << i << "\n"; //prints 257 (1 * 16 * 16 + 1)
}
Output:
257
Related
I need to convert characters from a string into int's then place them into a vector. I started by making a new string of the numbers without the spaces. I then want to iterate through the numbers in the result string and convert to int, then push into a vector. I am having issues with the negative numbers not converting to the right values. I commented out the vector part because I realized the issue is before that, the wrong values are going into the vector.
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string result = "";
string str = "8 3 -5 42 -1 0 0 -9 4 7 4 -4";
for(char c : str) {
if(c == ' ') {
continue;
}
else {
result += c;
}
}
cout << "result: " << result;
vector<int> lst;
//for(int x = 0; x < result.length(); x++) {
//lst.push_back(result[x] - '0');
//}
//testing the values being converted
int x = result[2] - '0';
cout << "\n" << x;
}
For example,
int x = result[0] - '0';
cout << "\n" << x;
gives me 8, which is the right conversion of the first number in the string.
but,
int x = result[2] - '0';
cout << "\n" << x;
gives me -3, which is not the -5 I am looking for. I am stuck on this and I cannot figure out why the negative numbers are not properly converting, or where the -3 is even coming from. Any help is appreciated, thank you.
Your input is: "8 3 -5 42 -1 0 0 -9 4 7 4 -4"
You put non-space characters into the result array, so:
result[0]->'8'
result[1]->'3'
result[2]->'-'
result[3]->'5'
So result[2] is - which has an ASCII code of 45. The zero digit has an ASCII code of 48. So result[2] - '0' is 45 minus 48 or -3.
You don't say why you expect -5. What character do you think is five less than the digit zero?
This question already has answers here:
How do I use an uint8_t with I/O streams while avoiding the char behavior?
(2 answers)
Closed 2 years ago.
I have implemented in C++ print_in_binary_format() function, which (as the name states) print 8-bit number in binary:
void print_in_binary_format(std::uint8_t number)
{
for (int bit_index = 7; bit_index >= 0; --bit_index) {
std::cout << ((number & (1U << bit_index)) ? '1' : '0');
}
std::cout << '\n';
}
But it doesn't work as supposed, i.e.:
Input: 2
Output: 00110010
Input: 0
Output: 00110000
I know that in C++ I could use bitset library, but it is not the case.
I would like to know what is wrong with this function, my brain is stuck!
There is whole program to test that:
#include <cstdint>
#include <iostream>
std::uint8_t read_user_number();
void print_in_binary_format(std::uint8_t number);
int main()
{
std::uint8_t number {};
number = read_user_number();
print_in_binary_format(number);
return EXIT_SUCCESS;
}
std::uint8_t read_user_number()
{
std::cout << "Enter a number (0-255): ";
std::uint8_t user_number {};
std::cin >> user_number;
return user_number;
}
void print_in_binary_format(std::uint8_t number)
{
for (int bit_index = 7; bit_index >= 0; --bit_index) {
std::cout << ((number & (1U << bit_index)) ? '1' : '0');
}
std::cout << '\n';
}
The problem is your input data. You are providing 2 or 0 as a character, not as a number.
Let me explain:
character '2' -> ASCII 0x32, 32 is the real input of your function, 00110010 is the bit representation of 0x32.
character '0' -> ASCII 0x30 has 00110000 as binary representation.
Hence the function above is working.
In order to solve the issue look at the way you are collecting the input data.
My 2 cents, Ste.
what is this function used for ? and it's not for the power function. :
#include<iostream>
using namespace std;
int main(){
int x,y;
cout<<(x^y)<<endl;/* this is the unkown (X^Y)*/
return 0;
}
The ^ operator is the bitwise XOR. Take for example 6 and 12
6 in binary is: 110
12 in binary is: 1100
The xor follows this rule: "The first or the second but not both". What does it mean? Its truth table should make it clear:
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
You can see that the only 1-bits are those where or A or B (but not both) are set.
Back to the first example:
A 1100 => 12
B 0110 => 6
A^B 1010 => 10
It's XOR. If you want more information about it see here https://en.wikipedia.org/wiki/Exclusive_or
Power function in c++ is
#include <math.h>
#include <iostream>
int main()
{
int x, y;
std::cout << "Give numbers " << std::endl;
std::cout << "x = ";
std::cin >> x;
std::cout << "y = ";
std::cin >> y;
std::cout << "Result = " << pow(x, y) << std::endl;
return 0;
}
Your version is XOR (logical operation) which is used to for example embedded systems etc.
I want to generate random numbers inside loop but results are always same numbers.
What I'm doing wrong? Thanks.
Code
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
const char duom[] = "U1.txt";
const char rez[] = "U1_rez.txt";
void num_gen(int & x, int & y);
int main(){
srand(time(NULL));
int x, y;
ifstream fd(duom);
fd >> x >> y;
fd.close();
ofstream fr(rez);
for(int j = 1; j <= 4; j++){
num_gen(x, y);
fr << x << " + " << y << " = "<< x + y << endl;
fr << x << " - " << y << " = "<< x - y << endl;
fr << x << " * " << y << " = "<< x * y << endl;
fr << x << " / " << y << " = "<< x / y << endl;
fr << "************" << endl;
}
fr.close();
return 0;
}
void num_gen(int & x, int & y){
x = 3 + (rand() % 10);
y = 3 + (rand() % 10);
}
Result
4 + 8= 12
4 - 8= -4
4 * 8= 32
4 / 8= 0
************
4 + 9= 13
4 - 9= -5
4 * 9= 36
4 / 9= 0
************
9 + 11= 20
9 - 11= -2
9 * 11= 99
9 / 11= 0
************
12 + 8= 20
12 - 8= 4
12 * 8= 96
12 / 8= 1
************
With the advent of C++11/14 you should actually give up using srand & rand & use the more efficient RANDOM NUMBER GENERATING MACHINES declared in the header #include<random>. Illustrating in a simple example :-
#include <iostream>
#include <random> // for default_random_engine & uniform_int_distribution<int>
#include <chrono> // to provide seed to the default_random_engine
using namespace std;
default_random_engine dre (chrono::steady_clock::now().time_since_epoch().count()); // provide seed
int random (int lim)
{
uniform_int_distribution<int> uid {0,lim}; // help dre to generate nos from 0 to lim (lim included);
return uid(dre); // pass dre as an argument to uid to generate the random no
}
int main()
{
for (int i=0;i<10;++i)
cout<<random(10)<<" ";
return 0;
}
One of the outputs of the above code is :-
8 5 0 4 2 7 9 6 10 8
See, the numbers vary from 0 to 10. Give your limits in uniform_int_distribution according to your desired output. This thing seldom fails & you can generate random numbers in greater ranges without worrying about outrageous outputs like you had.
Might be because the the random method is running with time of the computer. So if in the same 1/10000 of a second you computer do all process he need to do, you might read the same number since the random method haven't refresh the value. Try to put a sleep at the end of the for (like sleep(100)) and check if the values changed.
I think your code should generate different "pseudo" random numbers between 3 and 12 at each run, subject to that more of one second has elapsed between each run. Check if all this is really what you want.
Maybe you just run it much faster than the increase in a second when you call to time(NULL), which return the number of seconds since the epoch.
Anyway, your random numbers are not very good because you use the lower order bits. I transcript this excerpt from the rand() man page:
In Numerical Recipes in C: The Art of Scientific Computing (William H.
Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New
York: Cambridge University Press, 1992 (2nd ed., p. 277)), the follow-
ing comments are made:
"If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."
In C++, an octal number is defined by preceeding it with a 0, example:
01 = 1
010 = 8
014 = 12
So I was experimenting how working with Base 8 in c++ works, and tried adding to it with a loop, like so:
int base8Number = 00;
for (int i = 01; i < 011; i+=01)
{
base8Number += i;
cout << base8Number << '\n';
}
And apparently, C++ doesn't like working with octal numbers, the output I got is as follows:
1
3
6
10
15
21
28
36
The most obvious reason I know it's not working in Base 8, is the 28 output as a result, since the 8 number isn't used in Base 8.
So, my question: Can you work with Base 8 in c++, or is it just meant to be used as a constant, and if you can work with Base 8 in c++, how do you do it?
So first, let's remember that when we print numbers the way you're doing, they will be shown in decimal.
Now, let's rewrite your code without octal:
int base10Number = 0;
for (int i = 1; i < 9; i+=1)
{
base10Number += i;
cout << base10Number << '\n';
}
So let's now look at what your code is actually doing:
cout << 1 << "\n"; // 1
cout << 1 + 2 << "\n"; // 3
cout << 1 + 2 + 3 << "\n"; // 6
cout << 1 + 2 + 3 + 4 << "\n"; // 10
....
Which is what you're seeing. So no, there is no problem with how octal works in c++.
If you'd like you can use std::oct to tell std::cout to use octal printing. For example:
int main() {
std::cout << std::oct << 25 << "\n"; // Outputs: 31
}
Remember that "base" is a property of number representation, not the number itself. If you've got enough pegs to put one on each finger, then that is the same number of pegs regardless of whether you write 10, 012 0xA, or anything else.
Your code computes the numbers which would be shown in base 10 as 1, 3, 6, 10, 15, etc. You output them in base 10. To output them in base 8 use:
std::cout << std::oct << base8Number << std::endl;
There are a couple of things going on here.
Intrinsically, your computer operates in binary (base 2). When you do something like int foo = 10;, you are expressing the number 10 in decimal form because it's convenient for you to read it that way, but in the end the computer will still store it using binary, e.g. 1010.
If you were to use an octal literal (e.g. 012), then as far as the computer's concerned that's still just a 1010 binary constant - the only thing that's changed is its representation in the source code.
Finally, the last thing to realise is that the computer will by default output integers in base 10, because that's what's easy for people to read. It's still outputting the number 1010, just using the decimal representation of it.
Given all of the above, your code is entirely equivalent to doing the following, which you can verify for yourself produces the same output without using any octal:
int num = 0;
for (int i = 1; i < 9; i += 1) // Constants the same, just changed from octal representation to decimal.
{
num += i;
cout << num << '\n'; // Outputs in decimal, as with original program.
}
To get what you expect, try using the oct modifier:
int base8Number = 00;
for (int i = 01; i < 011; i+=01)
{
base8Number += i;
cout << oct << base8Number << '\n';
// ^--Here. Explicitly requests octal output.
}
This then explicitly requests that the computer output the values using octal.