473,734 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Conversions from decimal to binary,hex

My program converts decimal numbers from to binary and hexadecimal. I
am having trouble with my output which is supposed to be in a certain
format. Binary needs to be in the format of
XXXX XXXX for numbers 0 to 255. What am doing wrong or not doing with
my output?

Source code:
// code

#include <iostream>
#include <iomanip>

using namespace std;

void binary(int);
void hexdecimal(int) ;

int main()
{
int array[256];
int hex[256];
int i;

cout << "DECIMAL " << " BINARY " << " HEXADECIMAL " <<
" BCD" << endl;
cout << endl;
for(int i=0;i<256;i++)
{
array[i] = i;
cout << i;
binary(i);
hexdecimal(i);
cout<< endl;
}

return 0;
}
void binary(int i)
{
int rem;
if(i<=1)
{
cout << setw(8) << i;
return;
}
rem = i % 2;
binary(i >1);
cout << rem;
}

void hexdecimal(int i)
{
char buffer[33];
itoa(i,buffer,1 6);
cout << " ";
cout << setw(12) << buffer;

}

// end of code

This is what my output looks like for the first few

DECIMAL BINARY HEXADECIMAL

0 0 0
1 1 1
2 10 2
3 11 3
4 100 4
5 101 5
6 110 6
7 111 7
8 1000 8
9 1001 9
10 1010 a
11 1011 b

Thanks in advance

Sep 12 '07 #1
3 8846
<zg******@gmail .comwrote in message
news:11******** **************@ y42g2000hsy.goo glegroups.com.. .
My program converts decimal numbers from to binary and hexadecimal. I
am having trouble with my output which is supposed to be in a certain
format. Binary needs to be in the format of
XXXX XXXX for numbers 0 to 255. What am doing wrong or not doing with
my output?

Source code:
// code

#include <iostream>
#include <iomanip>

using namespace std;

void binary(int);
void hexdecimal(int) ;

int main()
{
int array[256];
int hex[256];
int i;

cout << "DECIMAL " << " BINARY " << " HEXADECIMAL " <<
" BCD" << endl;
cout << endl;
for(int i=0;i<256;i++)
{
array[i] = i;
cout << i;
binary(i);
hexdecimal(i);
cout<< endl;
}

return 0;
}
void binary(int i)
{
int rem;
if(i<=1)
{
cout << setw(8) << i;
return;
}
rem = i % 2;
binary(i >1);
cout << rem;
}

void hexdecimal(int i)
{
char buffer[33];
itoa(i,buffer,1 6);
cout << " ";
cout << setw(12) << buffer;

}

// end of code

This is what my output looks like for the first few

DECIMAL BINARY HEXADECIMAL

0 0 0
1 1 1
2 10 2
3 11 3
4 100 4
5 101 5
6 110 6
7 111 7
8 1000 8
9 1001 9
10 1010 a
11 1011 b

Thanks in advance
Look at setfill('0') in combination with setw(12)
Sep 12 '07 #2
On Sep 12, 3:26 am, zgfar...@gmail. com wrote:
My program converts decimal numbers from to binary and hexadecimal. I
am having trouble with my output which is supposed to be in a certain
format. Binary needs to be in the format of
XXXX XXXX for numbers 0 to 255. What am doing wrong or not doing with
my output?
Lot's of things:-).

I presume that this is more or less homework, or an exercise for
you to learn by. Otherwise, presumably, you would use the hex
manipulator to output the hex. (Regrettably, there is no binary
manipulator.)
Source code:
// code
#include <iostream>
#include <iomanip>
using namespace std;
Something to avoid in production code, of course.
void binary(int);
void hexdecimal(int) ;
Just wondering, do you want the values to really be signed?
(Not that it matters for your test values.)
int main()
{
int array[256];
int hex[256];
int i;
What are these declarations for, here? You never use hex or i
at all, and you only write to array, you never read it.
cout << "DECIMAL " << " BINARY " << " HEXADECIMAL " <<
" BCD" << endl;
That could be one single string, of course.
cout << endl;
for(int i=0;i<256;i++)
{
array[i] = i;
cout << i;
binary(i);
hexdecimal(i);
cout<< endl;
}
return 0;
}
void binary(int i)
{
int rem;
if(i<=1)
{
cout << setw(8) << i;
return;
}
rem = i % 2;
binary(i >1);
cout << rem;
}
Several general comments:

-- A function should never output to std::cout. Pass it an
std::ostream& as a parameter. Or have it return an
std::string.

-- You also don't take into consideration the fact that i might
be negative. If this is a pre-condition, then you should
have at least an assert; otherwise, you need to handle it.

-- Recursion is not particularly the best solution here;
although it can definitely be made to work, it handles
formatting very awkwardly. (It is a reasonable solution if
you generate non-formatted output, and then use a separate
routine to copy-format later. More on that below.)

-- You don't need the variable rem, either. Just output i % 2.

-- You definitely don't want the setw in the output in the if.
Each iteration outputs exactly one character. If the rest
worked (i.e. the condition in the if were correct), then
you'd have already output 7 digits before entering the if.

-- You're end condition doesn't take into account the number of
digits generated, at all.

-- You've no logic what so ever to generate the space in the
middle of the output.

If you're going to use recursion, and also want to format when
doing so, then you'll need information concerning the number of
digits and the format to be passed in each recursion. A
recursive solution which does both rapidly becomes painful.
void hexdecimal(int i)
{
char buffer[33];
itoa(i,buffer,1 6);
cout << " ";
cout << setw(12) << buffer;
}
The first two comments for binary also apply here. In addition,
there is no function itoa in C++.

Note that converting an int (or an unsigned int) to any base is
roughly the same. Without formatting, you can use either
recursion or iteration:

Iteration:

std::string
toString( unsigned int i, int base )
{
assert( base >= 2 && base <= 36 ) ;
std::string result ;
while ( i != 0 ) {
result += "0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ"[ i %
base ] ;
i /= base ;
}
std::reverse( result.begin(), result.end() ) ;
return result ;
}

Recursion:

std::string
toString( unsigned int i, int base )
{
std::string result ;
if ( i >= base ) {
result = toString( i / base, base ) ;
}
result += "0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ"[ i % base ] ;
return result ;
}

(Note that I've used unsigned int as an argument, to avoid the
issue of the sign.)

To ensure proper formatting, there are two solutions: do it
during the conversion, or use a copy-format after conversion.
To do it during converion, you have to pass the formatting
information to the "toString" function, above. Something like:

struct Spacing
{
int grouping ;
char sepChar ;
} ;

std::string
toString( unsigned int i, int base, Spacing const& fmt )
{
assert( base >= 2 && base <= 36 ) ;
std::string result ;
int generated = 0 ;
while ( i != 0 ) {
result += "0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ"[ i %
base ] ;
++ generated ;
if ( generated % fmt.grouping == 0 ) {
result += fmt.sepChar ;
}
i /= base ;
}
std::reverse( result.begin(), result.end() ) ;
return result ;
}

You can work out something similar for the recursive version if
you want, but note that the above uses an additional state
variable, which must be passed during recursion.

The alternative solution would be to use some sort of
copy-format function; a function which takes a format string
(e.g. something like the PICTURE clause in Cobol, or the format
string in a PRINT USING in Basic), and copies the unformatted
converted text using that, e.g.:

std::string
copyFormat( std::string const& format, std::string const& number )
{
std::string result ;
typedef std::string::co nst_reverse_ite rator
SrcIter ;
SrcIter src = number.rbegin() ;
for ( SrcIter fmt = format.rbegin() ;
fmt != format.rend() ;
++ fmt ) {
switch ( *fmt ) {
case '#' :
result.push_bac k( src == number.rend()
? ' '
: *src ++ ) ;
break ;

case '9' :
result.push_bac k( src == number.rend()
? '0'
: *src ++ ) ;
break ;

default:
result.push_bac k( *fmt ) ;
break ;
}
}
std::reverse( result.begin(), result.end() ) ;
return result ;
}

In this case, you're output in the loop in main would be
something like:

std::cout << std::setw( 12 ) << i
<< copyFormat( " 9999 9999", toString( i, 2 ) )
<< copyFormat( " ####", toString( i, 16 ) )
<< std::endl ;

(Note that all of the above code is just off the top of my head;
none of it has been tested, or even compiled. So there are
probably a few errors. But it should give you some ideas to
start with.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Sep 12 '07 #3

<zg******@gmail .comwrote in message...
My program converts decimal numbers from to binary and hexadecimal. I
am having trouble with my output which is supposed to be in a certain
format. Binary needs to be in the format of
XXXX XXXX for numbers 0 to 255. What am doing wrong or not doing with
my output?
// ------------
void ToBinary( unsigned char const val, std::ostream &out){
for( int i(7); i >= 0; --i ){
if( val & (1 << i) ) out << "1";
else out << "0";
if( 4 == i ) out << " ";
} // for(i)
} // ToBinary(unsign ed char const,ostream&)
// ------------
>
int main(){
int array[256];
cout<<"DECIMAL BINARY HEXADECIMAL BCD\n"<<endl;
for( size_t i(0); i < 256; ++i ){
array[i] = i;
cout << i;
// binary(i);

unsigned char numc( i & 0xFF );
ToBinary( numc, std::cout );
std::cout<<"\t" ;
hexdecimal(i);
cout<< endl;
}
return 0;
}
Look up 'std::bitset' for another way to do it.

--
Bob R
POVrookie
Sep 12 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
6146
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number. "Decimal Number" sometimes serves to distinguish Base 10 numbers, eg "15", from Base 2 numbers, Eg "1111". At other times "Decimal Number" serves to differentiate a number from an integer. For the rest of this post I shall only use either...
5
1981
by: Michael A. Covington | last post by:
Microsoft's documentation is a bit unclear, but is Decimal in fact a radix-100 (base-100) arithmetic data type (in which each byte ranges only from 0 to 99)? It should be straightforward to dump some Decimal values onto a binary file (or into a stream that writes into an array of bytes) and examine them.
687
23574
by: cody | last post by:
no this is no trollposting and please don't get it wrong but iam very curious why people still use C instead of other languages especially C++. i heard people say C++ is slower than C but i can't believe that. in pieces of the application where speed really matters you can still use "normal" functions or even static methods which is basically the same. in C there arent the simplest things present like constants, each struct and enum...
1
1645
by: lmh86 | last post by:
Should the following algorithm produce the binary equivalent of an inputed decimal value? ---------- cout << "Decimal value: "; cin >> Decimal; Binary = 0; Remainder = Decimal; for(Power = 4; Power = -1; Power--) { Remainder = Decimal - (pow(2,Power));
14
14298
by: me2 | last post by:
I am writing a little base conversion utility called base.c. This is what base does. $ base -127 Signed decimal: -127 Unsigned decimal: 4294967169 Hexidecimal: 0xffffff81 Octal: O37777777601 Binary: 1098 7654 3210 9876 5432 1098 7654 3210
28
5925
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly. See section 4.7 for Rounding issues.
2
4499
by: Tukeind | last post by:
Hello, I am receiving the following error: error C2065: 'to_binary' : undeclared identifier while running the code below. If anyone can help I'll appreciate it? Thank you, Tukeind
9
3477
by: Leo jay | last post by:
i'd like to implement a class template to convert binary numbers to decimal at compile time. and my test cases are: BOOST_STATIC_ASSERT((bin<1111,1111,1111,1111>::value == 65535)); BOOST_STATIC_ASSERT((bin<1111>::value == 15)); BOOST_STATIC_ASSERT((bin<0>::value == 0)); BOOST_STATIC_ASSERT((bin<1010, 0011>::value == 163)); you can find my implementation at:
0
28065
Frinavale
by: Frinavale | last post by:
Convert a Hex number into a decimal number and a decimal number to Hex number This is a very simple script that converts decimal numbers into hex values and hex values into decimal numbers. The example following this one demonstrates how to convert decimal numbers into binary values. A hex number is a string that contains numbers between 0-9 and characters A-F; where A = 10, B = 11, ..., F = 15. (For more information please look up...
0
8777
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9452
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9184
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6737
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6033
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4551
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4813
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2729
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.