WAP to convert octal to binary - c++

In a C++ program to convert octal numbers to binary, I was able to run the program, but the problem is the output is coming,
Enter number in octal: 1
1 in octal:1
But as we know octal is a 3 bit number so what to do to bring the result as 001?
For information, I declared a function, and used a return value of 'binary'(a variable I declared) in the function definition.
Will I declare the binary variable as binary [3]? Or if not, what is the correct way?

#include <iomanip>
cout << setfill('0') << setw(3) << binary

If leading zeros matter to you... this could sort of be a dup. See "How can I pad an int with leading zeros when using cout << operator?" ( How can I pad an int with leading zeros when using cout << operator? ).
Anyway, aside from (in spite of?) the lack of example code in the question... :-)
I would suggest looking at the answer from that post about printf(), which I find to be much more concise than cout formatting.
Try this (assuming your number is stored in a variable named 'i', adjust accordingly):
int i = 0113; // should yield decimal=75, hex=4B, and octal=113.
// important: note that we give printf 3 arguments after the string: i, i, i.
printf("decimal: %06d hex: %06x octal: %06o\n", i, i, i); // zero filled, all 6 long.
printf("decimal: %6d hex: %6x octal: %6o\n", i, i, i); // note lack of leading zeros, still 6 long.
printf("decimal: %d hex: %x octal: %o\n", i, i, i); // just as long as they need to be (1 to many).
This is one place (of many) to get some printf formatting info: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/format.html
fyi - Internally your integers are already in binary, and are already probably using 32 (or maybe 64) bits each... depending on whether they're shot, int, long and so on. So I suspect there isn't much to change your variable declarations.
The trick here is to understand that printf (or cout, if you prefer) generates the characters to represent the binary number (i, above) on your output. This is why the compiler wants you to use 123 for decimal, 0123 for octal (not the leading zero) and 0x123 for hex so it can convert them from characters in your source code (or input at run time) into the proper binary format in a given variable's memory.

Related

Why doesn't this function print all the char array as it takes it?

i was trying to convert from a char array to integers and the atoi function is working properly except when i put a zero in the first index...it didn't print it
#include<iostream>
using namespace std;
int main()
{
char arr[]= "0150234";
int num;
num=atoi(arr);
cout << num;
return 0;
}
I expect the output of 0150234 but the actual output is 150234
I think inside the atoi function you have typecasted the string to integer because of which the 0 gets removed. You can never get a 0 printed before a number since it doesn't make sense.
000001 will always be represented as 1.
I hope this clears your doubt.
Binary number representations (such as int) do not store leading 0s because there is an infinite number of them. Rather they store a fixed number of bits which may have some leading 0 bits.
You can still print the leading 0s if necessary:
std::cout << std::setw(4) << std::setfill('0') << 1 << '\n';
Output:
0001
You're confusing two ideas:
Numbers: These are abstract things. They're quantities. Your computer stores the number in a manner that you should not care about (though it's probably binary).
Representations: These are ways we display numbers to humans, like "150234", or "0x24ADA", or "one hundred and fifty thousand, two hundred and thirty four". You pick a representation when you convert to a string. When streaming to std::cout a representation is picked for you by default, but you can choose your own representation using I/O manipulators, as Maxim shows.
The variable num is a number, not a representation of a number. It does not contain the information «display this as "0150234"». That's what arr provides, because it is a string, containing a representation of a number. So, if that leading zero in the original representation is important to you, when you print num, you have to reproduce that representation yourself.
By the way…
Usually, in the programming world, and particularly in C-like source code:
When we see a string like "150234" we assume that it is the decimal (base-10) representation of a number;
When we see a string like "0x24ADA" (with a leading 0x) we assume that it is the hexadecimal (base-16) representation of a number;
When we see a string like "0150234" (with a leading 0) we assume that it is the octal (base-8) representation of a number.
So, if you do add a leading zero, you may confuse your users.
FYI the conventional base-8 representation of your number is "0445332".

C++ : storing a 13 digit number always fails

I'm programming in C++ and I have to store big numbers in one of my exercices.
The biggest number i have to store is : 9 780 321 563 842.
Each time i try to print the number (contained in a variable) it gives me a wrong result (not that number).
A 32bit type isn't enough since 2^32 is a 10 digit number and I have to store a 13 digit number. But with 64 bits you can respresent a number that has 20digits. So I tried using the type "uint64_t" but that didn't work for me and I really don't understand why.
So I searched on the internet to find which type would be sufficient for my variable to fit in. I saw on this forum persons with the same problem but they solved it using long long int or long double as type. But none worked for me (neither did long float).
I really don't know which other type could store that number, as I tried a lot but nothing worked for me.
Thanks for your help! :)
--
EDIT : The code is a bit long and complex and would not matter for the question, so this is actually what I do with the variable containing that number :
string barcode_s = "9780321563842";
uint64_t barcode = atoi(barcode_s.c_str());
cout << "Barcode is : " << barcode << endl;
Off course I don't put that number in a variable (of type string) "barcode_s" to convert it directly to a number, but that's what happen in my program. I read text from an input file and put it in "barcode_s" (the text I read and put in that variable is always a number) and then I convert that string to a number (using atoi).
So i presume the problem comes from the "atoi" function?
Thanks for your help!
The problem is indeed atoi: it returns an int, which is on most platforms a 32-bits integer. Converting to uint64_t from int will not magically restore the information that has been lost.
There are several solutions, though. In C++03, you could use stringstream to handle the conversion:
std::istringstream stream(barcode_s);
unsigned long barcode = 0;
if (not (stream >> barcode)) { std::abort(); }
In C++11, you can simply use stoul or stoull:
unsigned long long const barcode = std::stoull(barcode_s);
Your number 9 780 321 563 842 is hex 8E52897B4C2, which fits into 44 bits (4 bits per hex digit), so any 64 bit integer, no matter if signed or unsigned, will have space to spare. 'uint64_t' will work, and it will even fit into a 'double' with no loss of precision.
It follows that the remaining issue is a mistake in your code, usually that is either an accidental conversion of the 64 bit number to another type somewhere, or you are calling the wrong fouction to print a 64 bit integer.
Edit: just saw your code. 'atoi' returns int. As in 'int32_t'. Converting that to 'unit64_t' will not reconstruct the 64 bit number. Have a look at this: http://msdn.microsoft.com/en-us/library/czcad93k.aspx
The atoll () function converts char* to a long long.
If you don't have the longer function available, write your own in the mean time.
uint64_t result = 0 ;
for (unsigned int ii = 0 ; str.c_str()[ii] != 0 ; ++ ii)
{
result *= 10 ;
result += str.c_str () [ii] - '0' ;
}

Invert 7th bit of hex string C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Change bit of hex number with leading zeros in C++,(C)
I have this number in hex string:
002A05(7th bit is set to 0)
I need to invert 7-th bit of this number, so after conversion I will get
022A05
But in case
ABCDEF(7th bit is set to 1)
I need to get
A9CDEF
But it has to work with every 6 chars hex number.
It need to be 7th bit from left. I'm trying convert OUI to modified EUI64
I tried converting hex string to integer via strtol, but that function strip leading zeros.
Please help me how can I solve it.
Simplest way, but not necessarily the cleanest;
Since only one char is affected, you can just do it using a simple string manipulation; assuming your input is in uppercase in the string input;
input[1] = "23016745AB*******89EFCD"[input[1]-48];
#include <stdio.h>
void flipme(char *buf, const char *inBuf)
{
int x;
sscanf(inBuf, "%x", &x);
x ^= 1 << 17;
sprintf(buf, "%06X", x);
}
int main(void)
{
char buf[16];
flipme(buf, "002A05");
printf("002A05->%s\n", buf);
flipme(buf, "ABCDEF");
printf("ABCDEF->%s\n", buf);
}
Output:
002A05->022A05
ABCDEF->A9CDEF
You wrote:
I tried converting hex string to integer via strtol, but that function strip leading zeros.
The strtol function converts it to a number. It doesn't mean anything to say it strips leading zeroes because numbers don't have leading zeroes -- "6" and "06" are two different ways of writing the same number. If you want leading zeroes when you print it, you can add them then.
num ^ 0x020000
^ is the bitwise xor operator.
Given an integer x, the number with 3rd bit inverted is x ^ 2.
The rest of the answer was given to you earlier.
Note: in the question the bits are counted from highest to lowest, starting at 1. Then 7th bit of a 6 digit hex number is the 3rd bit of its 2nd highest character. Normally bits are counted from lowest to highest, starting from 0 though.

C++ for loop, while loop, and do while loop to generate a table of decimal numbers

I need help for a starting point, really. We must use these 3 loops to generate a table of decimal numbers, as well as the binary, octal, and hexadecimal equivalents of the decimal numbers, in the range 1-256. Help would be greatly appreciated.
If you don't know where to start that's... not a good sign. Perhaps you should get together with your teacher so that you don't fall behind.
Anyway, the basic idea will be:
for loop counting from 1 to 256
write counter in decimal form
write counter in binary form
write counter in hex form
write counter in octal form
end loop
You really don't need three loops, though you can break it into three if you have to. You can pass different format specifiers to printf and the like to format your output.
Look at this page to learn about specifiers: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
if you use printf and include %d then you are going to print a decimal. If you use %x you will get the unsigned Hexidecimal of the same number.
for example:
int i;
for(i=1;i<=256;i++){
printf("the number %d in dec: %d",i,i); \\prints i
printf("the number %d in hex: %x",i,i); \\prints i in hex.
printf("the number %d in oct: %o",i,i); \\prints i in oct.
}
OR
int i = 1;
while(i<=256) {
...
i++;
}
OR
int i = 1;
do {
...
i++;
} while (i<=256);
This page talks about the types of loops: http://www.tutorialspoint.com/cplusplus/cpp_loop_types.htm

input containing leading zeroes

In c++ will their be any error if we input an integer containing leading zereos.
for eg:
int a;
cin>>a;
we give an input 00 or 01.
or inputing with the help of string for this is a better idea.
Integers (or floats for that matter) do not have leading zeroes. If you want to keep the leading zeroes then you have to read the input as a string instead, and convert it to number when needed. Or you can use formatting to add leading zeroes when printing results.
In c++ will their be any error if we input an integer containing leading zereos.
You might not get what you expect, depending on the settings of the input stream's format flags. The default is to expect user input to always be in decimal. Leading zeros have no effect. What if we turn that off by calling std::cin.unsetf()?
int main () {
int i;
std::cin.unsetf (std::ios::dec);
while (std::cin >> ii) {
std::cout << i << "\n";
}
}
The output will be 25 if you enter 25, but if you enter 025 the output is 21. That's because C++ now interprets a leading zero on input to mean the number that follows is in octal (or in hexadecimal in the case of a leading 0x or leading 0X).
Leading Zeros will be trimmed off. It wont be stored in the memory.