Exploring bases through C++
Objectives
We would like to :Notes
- Let's use some C++ tricks to try to get a deeper insight into binary.
- Log into prog1, we will need c++20 for one small bit.
- Given a number, can we print out the binary/hex/octal representation?
- cout tricks:
- The stream modifiers, dec, hex, oct
-
cout << std::hex << number
-
- These change the state of the stream.
- It defaults to
dec - So you will want to reset it to dec after you are done in one of the other formats.
- see this reference.
- Write a program function that prints out several numbers in hex, octal and decimal.
- Use the number 1024+512+256+32 + 8 + 4 +1
- The stream modifiers, dec, hex, oct
- What are these hex and octal things?
- In c++20, changed is 23 is std::format
- reference
- This will act like printf
- It takes a format string
- And a value
- And returns the value formatted according to the string.
- We don't care about much of this now
- But there is a binary specifier
-
#include < format > ... cout << std::format("{:b}",number) << endl;
- Add this to your program, print the number in binary
- You will need to add -std=c++20 and be running on prog1
- Does this match the previous output.
- Prove it to me.
- That is nice but here are two other pieces of information you might want for the next exercise
-
&is the bitwise and- It will and each bit of the data.
- For example 1011 1010 & 1001 0110 = 1001 0010
- Write a program to compute and print this.
-
<<for integers is the bitwise shift left operator.-
1 << 1= 10 (or 2) -
101 << 2= 10100 - It is essentially a multiply by 2 operator.
-
101 >> 1= 10 - This is the bitwise shift right, or divide by 2.
-
-
size_of(expr)andsize_of(type)- reference.
- Returns the size, in bytes of the operator.
-
- Write a function that will use
&and<<to convert an integer type to the equivalent binary bit string. - With just a little thought, you can make this work with negative numbers too.
-