473,545 Members | 2,032 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 8835
<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
6113
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...
5
1972
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
22970
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...
1
1640
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
14219
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
5833
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...
2
4489
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
3464
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...
0
28047
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
7475
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7921
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7437
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7771
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...
0
4958
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...
0
3465
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...
0
3446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1900
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.