473,387 Members | 1,548 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

want a better version of this

Hi, can somebody help me out with a better version of the following
functions which only convert decimal integer to it's corresponding
binary form. the
problem i'm having now is that I can't figure out how to handle when 0
is
passed as parameter in only one function, my code below have to add
one more function to handle this situation, any help is appreciated,
thanx.
char *Dec2Bin(const int decimal) {

char *binary=new char[64];
int dividend,i;

dividend=decimal;
for(i=0;dividend!=0;++i) {
binary[i]=(dividend&1)+'0'; // (a % b) == (a & (b-1))
dividend>>=1;
}
binary[i]='\0';

return strrev(binary);
}

char *Decimal2Binary(const int decimal) {
return (decimal==0)?"0":Dec2Bin(decimal);
}
Nov 14 '05 #1
20 1819
In 'comp.lang.c', ru****@sohu.com (sugaray) wrote:
char *binary=new char[64];


There is no 'new' in C. Please repost to the appropriate newsgroup. It seems
that C is not your langage.

If you insist in writing your code in C, please change it so that it uses C
functions and instructions.

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #2
Emmanuel Delahaye wrote:
In 'comp.lang.c', ru****@sohu.com (sugaray) wrote:
char *binary=new char[64];


There is no 'new' in C.


It's a perfectly valid identifier name (albeit used in a rather strange and
syntactically erroneous manner in the code you quote here). In fact, I
often use it myself in code such as:

FOO *prefix_CreateFoo(args...)
{
FOO *new = malloc(sizeof *new);
if(new != NULL)
{
...set up valid FOO instance...
}
return new;
}

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #3
sugaray wrote:

Hi, can somebody help me out with a better version of the following
functions which only convert decimal integer to it's corresponding
binary form. the
problem i'm having now is that I can't figure out how to handle when 0
is
passed as parameter in only one function, my code below have to add
one more function to handle this situation, any help is appreciated,
thanx.

char *Dec2Bin(const int decimal) {


/* BEGIN bitstr.c */

#include <stdio.h>
#include <limits.h>

#define E_TYPE float
#define STRING " %s = %f\n"

typedef E_TYPE e_type;

char *bitstr(char *, void const *, size_t);

int main(void)
{
e_type e, d;
char ebits[CHAR_BIT * sizeof e + 1], *s;

s = STRING;
for (e = 0.2f; 0.75 > e; e += 0.125) {
bitstr(ebits, &e, sizeof e);
printf(s, ebits, e);
}
for (d = 2; 20000 > d; d *= 2) {
for (e = d - 1; 0.75 > e - d; e += 0.5) {
bitstr(ebits, &e, sizeof e);
printf(s, ebits, e);
}
}
return 0;
}

char *bitstr(char *str, const void *obj, size_t n)
{
unsigned char mask;
const unsigned char *byte = obj;
char *const ptr = str;

while (n-- != 0) {
mask = ((unsigned char)-1 >> 1) + 1;
do {
*str++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask != 0);
}
*str = '\0';
return ptr;
}

/* END bitstr.c */
--
pete
Nov 14 '05 #4
In 'comp.lang.c', Richard Heathfield <in*****@address.co.uk.invalid>
wrote:
There is no 'new' in C.


It's a perfectly valid identifier name (albeit used in a rather strange
and syntactically erroneous manner in the code you quote here). In fact,
I often use it myself in code such as:

FOO *prefix_CreateFoo(args...)
{
FOO *new = malloc(sizeof *new);
if(new != NULL)
{
...set up valid FOO instance...
}
return new;
}


I prefer to use 'this', in this case!

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #5
> Emmanuel Delahaye wrote:
In 'comp.lang.c', ru****@sohu.com (sugaray) wrote:
char *binary=new char[64];


There is no 'new' in C.


It's a perfectly valid identifier name (albeit used in a rather strange and
syntactically erroneous manner in the code you quote here). In fact, I
often use it myself in code such as:

FOO *prefix_CreateFoo(args...)
{
FOO *new = malloc(sizeof *new);
if(new != NULL)
{
...set up valid FOO instance...
}
return new;
}

You can use:

Char* binary = (char*)malloc(sozeof(char)*64); // allocate 64 times space
for a char
assert(binary); // make sure everything went ok (Memoryoverflow asf.)
// donąt forget when you donąt use binary anymore
free(binary);

Nov 14 '05 #6
Georg Troxler wrote:
You can use:

Char
Undefined type.
* binary = (char*)
Unnecessary cast.

malloc(sozeof(char)

Undeclared macro, sozeof
*64); // allocate 64 times space
If that's what you want to do, use:

char *binary = malloc(64);

or, perhaps:

char *binary = malloc(64 * sizeof *binary);

for a char
Illegal syntax for for-loop. (Hint: if you must use BCPL/C99 comments, make
sure your lines don't wrap!)

assert(binary); // make sure everything went ok (Memoryoverflow asf.)


This is a lousy use of assert. Assertions are best used for asserting
conditions that /must/ be true if and only if the programmer didn't screw
up. Furthermore, assert(pointerexpression) is not portable to C90.

Far better to check for NULL and handle the out-of-memory condition
robustly.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #7
Georg Troxler wrote:
Char* binary = (char*)malloc(sozeof(char)*64); // allocate 64 times space
for a char #include <stdlb.h>
somewhere

char* binary=malloc(sizeof(char)*64);
or:
char* binary=malloc(64);
assert(binary); // make sure everything went ok (Memoryoverflow asf.)

I don't think this is a good idea.
Imagine the following code:

#define NDEBUG
#include <assert.h>
#include <stdlib.h>
int main(void)
{
char *c;

c=malloc(64);
assert(c);

strcpy(p,"hello");

return 0;
}

In this code strcpy is also executed if c==NULL.
So I do think it is better to use:
if (!c) { /* or if (c==NULL) whatever you prefer */
/*some error handling here*/
}

or

if (c) { /* or if (c!=NULL) */
/*do something with c*/
}

-rb
--
Ro*************@rbdev.net
Nov 14 '05 #8
Robert Bachmann wrote:
if (c) { /* or if (c!=NULL) */
/*do something with c*/ I meant: /* do something with *c */ }


--
Ro*************@rbdev.net
Nov 14 '05 #9
In 'comp.lang.c', Georg Troxler <ge***********@yaksoft.com> wrote:
You can use:

Char* binary = (char*)malloc(sozeof(char)*64); // allocate 64 times
space for a char
(assuming typos are fixed) A complicated way of writing

char* binary = malloc(64);
assert(binary);
And what happens in release mode when NDEBUG is defined? Nothing. It's bad!
// donąt forget when you donąt use binary anymore
free(binary);


Agreed.

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #10
Georg Troxler wrote:

You can use:

Char* binary = (char*)malloc(sozeof(char)*64); // allocate 64 times space
for a char
assert(binary); // make sure everything went ok (Memoryoverflow asf.)


What the hell language is this? You _may_ mean
char *binary = malloc(64); /* note the case of 'char', the absence of the
superfluous cast, the absence of the
tautological and misspelled 'sozeof(char) *'
*/
if (!binary) { /* handle error */ }

--
Martin Ambuhl
Nov 14 '05 #11
In article <Xn***************************@213.228.0.75>, em**********@noos.fr
says...
In 'comp.lang.c', Richard Heathfield <in*****@address.co.uk.invalid>
wrote:
There is no 'new' in C.


It's a perfectly valid identifier name (albeit used in a rather strange
and syntactically erroneous manner in the code you quote here). In fact,
I often use it myself in code such as:

FOO *prefix_CreateFoo(args...)
{
FOO *new = malloc(sizeof *new);
if(new != NULL)
{
...set up valid FOO instance...
}
return new;
}


I prefer to use 'this', in this case!


I suppose this is a good way to make sure you code isn't accidentally
used with a C++ compiler?
--
Randy Howard
2reply remove FOOBAR

Nov 14 '05 #12
Randy Howard wrote:
> FOO *prefix_CreateFoo(args...)
> {
> FOO *new = malloc(sizeof *new);
> if(new != NULL)
> {
> ...set up valid FOO instance...
> }
> return new;
> }


I prefer to use 'this', in this case!


I suppose this is a good way to make sure you code isn't accidentally
used with a C++ compiler?


Yes, precisely. C and C++ are divided by a common syntax. It's important not
to mix them up accidentally.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #13
In 'comp.lang.c', Randy Howard <ra**********@FOOmegapathdslBAR.net> wrote:
I prefer to use 'this', in this case!


I suppose this is a good way to make sure you code isn't accidentally
used with a C++ compiler?


He he! I'm not supposed to know a word about C++. But for what you have
suggested, I put this on my sources (.c only)

#ifdef __cplusplus
#error This source file is not C++ but rather C. Please use a C-compiler
#endif

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #14
Emmanuel Delahaye wrote:
In 'comp.lang.c', Randy Howard <ra**********@FOOmegapathdslBAR.net> wrote:
I prefer to use 'this', in this case!


I suppose this is a good way to make sure you code isn't accidentally
used with a C++ compiler?


He he! I'm not supposed to know a word about C++. But for what you have
suggested, I put this on my sources (.c only)

#ifdef __cplusplus
#error This source file is not C++ but rather C. Please use a C-compiler
#endif


That's fine for C99, but IIRC there is no restriction on C90 compilers
defining __cplusplus for whatever dastardly purpose they choose. Therefore,
tempting as your suggestion is, I cannot adopt it myself.

Of course, I could do this:

static int new;

at the top of every C file. :-)

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #15
In article <40******@news2.power.net.uk>, in*****@address.co.uk.invalid says...
Emmanuel Delahaye wrote:
In 'comp.lang.c', Randy Howard <ra**********@FOOmegapathdslBAR.net> wrote:
I prefer to use 'this', in this case!

I suppose this is a good way to make sure you code isn't accidentally
used with a C++ compiler?
He he! I'm not supposed to know a word about C++. But for what you have
suggested, I put this on my sources (.c only)

#ifdef __cplusplus
#error This source file is not C++ but rather C. Please use a C-compiler
#endif


That's fine for C99, but IIRC there is no restriction on C90 compilers
defining __cplusplus for whatever dastardly purpose they choose. Therefore,
tempting as your suggestion is, I cannot adopt it myself.


Now, that is pedantic. :-)
Of course, I could do this:

static int new;

at the top of every C file. :-)


Well, you could at least do this...

static int new; /* Hey! this file is NOT valid C++, don't even try. */

and then way down at the bottom somewhere....

static int this; /* Hello! I warned you, do you never give up? */

--
Randy Howard
2reply remove FOOBAR

Nov 14 '05 #16
Richard Heathfield wrote:
.... snip ...
Of course, I could do this:

static int new;

at the top of every C file. :-)


Maybe:

static char this, class, new; /* why waste space */

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #17
Randy Howard wrote:
In article <40******@news2.power.net.uk>, in*****@address.co.uk.invalid
says...
Emmanuel Delahaye wrote:
> #ifdef __cplusplus
> #error This source file is not C++ but rather C. Please use a
> #C-compiler endif


That's fine for C99, but IIRC there is no restriction on C90 compilers
defining __cplusplus for whatever dastardly purpose they choose.
Therefore, tempting as your suggestion is, I cannot adopt it myself.


Now, that is pedantic. :-)


Of course. If we're going to discuss C, we might as well discuss it
properly.
--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #18

"sugaray" <ru****@sohu.com> wrote in message
news:ad**************************@posting.google.c om...
Hi, can somebody help me out with a better version of the following
functions which only convert decimal integer to it's corresponding
binary form. the
problem i'm having now is that I can't figure out how to handle when 0
is
passed as parameter in only one function, my code below have to add
one more function to handle this situation, any help is appreciated,
thanx.
char *Dec2Bin(const int decimal) {

char *binary=new char[64];
int dividend,i;

dividend=decimal;
for(i=0;dividend!=0;++i) {
binary[i]=(dividend&1)+'0'; // (a % b) == (a & (b-1))
dividend>>=1;
}
binary[i]='\0';

return strrev(binary);
}

char *Decimal2Binary(const int decimal) {
return (decimal==0)?"0":Dec2Bin(decimal);
}


Why not fill the string from the left, thus avoiding the need to do strrev ?
Something like this?

char *Dec2Bin(const unsigned int decimal) {
int i,num_bits;
char *binary;

num_bits=sizeof(int)*8;
binary=calloc(1,num_bits+1);

for(i=num_bits;i>=0;i--)
binary[num_bits-i]=((1<<i)&decimal)+'0';

return binary;
}

If you don't want the trailing '0's then add a flag which gets set when the
first non zero bit is reached and check against this flag inside your inner
loop so that all future '0's get written.

Note I have also changed the function argument to unsigned int since I think
there might be some implementation issues with using signed integers..

Sean

Nov 14 '05 #19

"Sean Kenwrick" <sk*******@hotmail.com> wrote in message
news:bv**********@sparta.btinternet.com...

"sugaray" <ru****@sohu.com> wrote in message
news:ad**************************@posting.google.c om...
Hi, can somebody help me out with a better version of the following
functions which only convert decimal integer to it's corresponding
binary form. the
problem i'm having now is that I can't figure out how to handle when 0
is
passed as parameter in only one function, my code below have to add
one more function to handle this situation, any help is appreciated,
thanx.
char *Dec2Bin(const int decimal) {

char *binary=new char[64];
int dividend,i;

dividend=decimal;
for(i=0;dividend!=0;++i) {
binary[i]=(dividend&1)+'0'; // (a % b) == (a & (b-1))
dividend>>=1;
}
binary[i]='\0';

return strrev(binary);
}

char *Decimal2Binary(const int decimal) {
return (decimal==0)?"0":Dec2Bin(decimal);
}
Why not fill the string from the left, thus avoiding the need to do strrev

? Something like this?

char *Dec2Bin(const unsigned int decimal) {
int i,num_bits;
char *binary;

num_bits=sizeof(int)*8;
binary=calloc(1,num_bits+1);

for(i=num_bits;i>=0;i--)
binary[num_bits-i]=((1<<i)&decimal)+'0';

return binary;
}

If you don't want the trailing '0's then add a flag which gets set when the first non zero bit is reached and check against this flag inside your inner loop so that all future '0's get written.

Note I have also changed the function argument to unsigned int since I think there might be some implementation issues with using signed integers..

Sean

There is an error in the above it should read something like:

binary[num_bits-i]=((1<<i)&decimal)?'1':'0';

Sean

Nov 14 '05 #20
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:40******@news2.power.net.uk...
Randy Howard wrote:
In article <40******@news2.power.net.uk>, in*****@address.co.uk.invalid
says...
Emmanuel Delahaye wrote:

> #ifdef __cplusplus
> #error This source file is not C++ but rather C. Please use a
> #C-compiler endif

That's fine for C99, but IIRC there is no restriction on C90 compilers
defining __cplusplus for whatever dastardly purpose they choose.
Therefore, tempting as your suggestion is, I cannot adopt it myself.


Now, that is pedantic. :-)


Of course. If we're going to discuss C, we might as well discuss it
properly.


N847 seems to say there _was_ an agreed proposal for C90 (re not defining
__cplusplus) which got "lost".

Personally, that's near enough for me. We all make the occasional clerical
errors. That shouldn't distract us... ;-)

--
Peter
Nov 14 '05 #21

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

Similar topics

21
by: Michele Simionato | last post by:
I often feel the need to extend the string method ".endswith" to tuple arguments, in such a way to automatically check for multiple endings. For instance, here is a typical use case: if...
3
by: Chris Cioffi | last post by:
I started writing this list because I wanted to have definite points to base a comparison on and as the starting point of writing something myself. After looking around, I think it would be a...
5
by: mr.iali | last post by:
Hi Everyone I would like to get into software developent using a programming language like c++, java or pl/sql for oracle. I have no idea where to start from. Which language is there more...
11
by: Michael B. | last post by:
I'm still learning C so I've written a simple app which lets you make a contact list (stored as a linked list of structs), write it to a file, and read it back. It works fine, but I notice in my...
182
by: Jim Hubbard | last post by:
http://www.eweek.com/article2/0,1759,1774642,00.asp
20
by: Parag | last post by:
Hi, I am trying to figure out best testing tool for my project. I have narrowed down my requirements to two tools NUNIT and VSTS unit. But I have used neither and I have to use only one of them....
4
by: Chris F Clark | last post by:
Please excuse the length of this post, I am unfortunately long-winded, and don't know how to make my postings more brief. I have a C++ class library (and application generator, called Yacc++(r)...
1
by: axs221 | last post by:
My company I work for uses VBA for Access to program one of our projects. We just now set up the Subversion version control system for our various projects. It works great for our VB6 and .NET...
1
by: Vivienne | last post by:
Hi there This is a hard problem that I have - I have only been using sql for a couple of weeks and have gone past my ability level quickly! The real tables are complex but I will post a simple...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.