473,404 Members | 2,213 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,404 software developers and data experts.

convert dec number to HEX and oct and bin without c library function

Hi, all

I'm now working on a program which will convert dec number to
hex and oct and bin respectively, I've checked the clc but with no
luck, so can anybody give me a hit how to make this done without
strtol or s/printf function.

Thanks,

whatluo.

Nov 14 '05 #1
7 7056
whatluo wrote:
Hi, all

I'm now working on a program which will convert dec number to
hex and oct and bin respectively, I've checked the clc but with no
luck, so can anybody give me a hit how to make this done without
strtol or s/printf function.


Homework? Well, here's a hint: With pencil and paper,
how would you convert "54321 seconds" to hours, minutes,
and seconds? Go ahead, do it -- and while you do it, ask
yourself what you're doing at each step, and why.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #2
whatluo wrote:

I'm now working on a program which will convert dec number to
hex and oct and bin respectively, I've checked the clc but with no
luck, so can anybody give me a hit how to make this done without
strtol or s/printf function.


I just happen to have this lying about:

/* base2txt.h. Public domain by C.B. Falconer, 2005-05-12. */
/* Output values to a text stream. No buffers needed */

#ifndef H_base2txt_h
# define H_base2txt_h
# ifdef __cplusplus
extern "C"
{
# endif

#include <stdio.h>

/* ----------------------- */

/* Convert unsigned value to stream of digits in base base.
A NULL value for f returns a char count with no output
Returns count of chars. output
return is negative for any output error */
int unum2txt(unsigned long n, unsigned int base, FILE *f);

/* ----------------------- */

/* Convert signed value to stream of digits in base base.
A NULL value for f returns a char count with no output
Returns count of chars. output
return is negative for any output error */
int num2txt(long n, unsigned int base, FILE *f);

/* ----------------------- */

/* Convert unsigned value to stream of decimal digits in fld.
A NULL value for f returns a char count with no output
A negative fld left justifies, else right.
Returns count of chars. output
return is negative for any output error */
int unum2fld(unsigned long n, int fld, FILE *f);

/* ----------------------- */

/* Convert signed value to stream of decimal digits in fld.
A NULL value for f returns a char count with no output
A negative fld left justifies, else right.
Returns count of chars. output
return is negative for any output error */
int num2fld(long n, int fld, FILE *f);

# ifdef __cplusplus
}
# endif
#endif
/* base2txt.c. Public domain by C.B. Falconer, 2005-05-12. */
/* <http://cbfalconer.home.att.net> */
/* Output values to a text stream. No buffers needed */

/* To compile a test version use -DTESTING with gcc */
/* To avoid recursion use -DNORECURSE with gcc. This */
/* may be useful on some non-conforming systems. */

#include "base2txt.h"

/* ----------------------- */

/* Convert unsigned value to stream of digits in base
A NULL value for f returns a char count with no output
Returns count of chars. output
return is negative for any output error */
int unum2txt(unsigned long n, unsigned int base, FILE *f)
{
/* MUST be a power of 2 in length */
static char hexchars[] = "0123456789abcdef";

/* allow for terminal '\0' */
#define MAXBASE (sizeof(hexchars)-1)
#ifdef NORECURSE
#include <limits.h>
int count, ix;

/* sufficient for a binary expansion */
char buf[CHAR_BIT * sizeof(long)];
#else
int count, err;
#endif

if ((base < 2) || (base > MAXBASE)) base = 10;
#ifdef NORECURSE
count = ix = 0;
do {
buf[ix++] = hexchars[(n % base) & (MAXBASE-1)];
} while ((n = n / base));
while (ix--) {
count++;
if (f && (putc(buf[ix], f) < 0)) return -count;
}
#else
count = 1;
if (n / base) {
if ((err = unum2txt(n / base, base, f)) < 0) return err;
else count += err;
}
if (f && (putc(hexchars[(n % base) & (MAXBASE-1)], f) < 0))
return -count;
#endif
return count;
} /* unum2txt */

/* ----------------------- */

/* Convert signed value to stream of digits in base
A NULL value for f returns a char count with no output
Returns count of chars. output
return is negative for any output error */
int num2txt(long n, unsigned int base, FILE *f)
{
int count, err;
unsigned long val;

val = n; count = 0;
if (n < 0) {
count++; val = -(unsigned long)n;
if (f && (putc('-', f) < 0)) return - count;
}
err = unum2txt(val, base, f);
if (err < 0) return err - count;
return err + count;
} /* num2txt */

/* ----------------------- */

/* Negative return if i/o error occurs */
/* Returns number of blanks output attempted */
static int putblks(int count, FILE *f)
{
int ix;

if (f && (count > 0)) {
for (ix = 0; ix < count; ix++) {
if (putc(' ', f) < 0) return -ix - 1;
}
return ix;
}
else return 0;
} /* putblks */

/* ----------------------- */

/* Convert unsigned value to stream of decimal digits in fld.
A NULL value for f returns a char count with no output
A negative fld left justifies, else right.
Returns count of chars. output
return is negative for any output error */
int unum2fld(unsigned long n, int fld, FILE *f)
{
int err, digs, blanks;

if (fld >= 0) { /* right justify in field */
digs = unum2txt(n, 10, NULL);
if (0 > (blanks = putblks(fld - digs, f))) return blanks;
if (0 > (err = unum2txt(n, 10, f))) return err - blanks;
else return err + blanks;
}
else { /* left justify */
if ((digs = unum2txt(n, 10, f)) < 0) return digs;
if (0 > (blanks = putblks(fld - digs, f)))
return blanks - digs;
else return blanks + digs;
}
} /* unum2fld */

/* ----------------------- */

/* Convert signed value to stream of decimal digits in fld.
A NULL value for f returns a char count with no output
A negative fld left justifies, else right.
Returns count of chars. output
return is negative for any output error */
int num2fld(long n, int fld, FILE *f)
{
int err, digs, blanks;

if (fld >= 0) { /* right justify in field */
digs = num2txt(n, 10, NULL);
if (0 > (blanks = putblks(fld - digs, f))) return blanks;
if (0 > (err = num2txt(n, 10, f))) return err - blanks;
else return err + blanks;
}
else { /* left justify */
if ((digs = num2txt(n, 10, f)) < 0) return digs;
if (0 > (blanks = putblks(fld - digs, f)))
return blanks - digs;
else return blanks + digs;
}
} /* num2fld */

#ifdef TESTING

/* ----------------------- */

/* This does some questionable things in order to get values to
display. This doesn't affect the validity of the routines */
int main(int argc, char **argv)
{
unsigned int base;
long num;
int fieldused;

if ((argc < 3) || (1 != sscanf(argv[1], "%u", &base)))
puts("Usage: base2txt base value [value ...]\n"
" where the value list is in decimal");
else {
printf("Dec.Input Base %u value [digs]\n", base);
while (argc > 2) {
sscanf(argv[--argc], "%ld", &num);
printf("%11s .", argv[argc]);
fieldused = unum2txt(num, base, stdout);
if (fieldused != unum2txt(num, base, NULL))
fputs("*ERROR*", stdout);
printf(". [%d] .", fieldused);
fieldused = num2txt(num, base, stdout);
if (fieldused != num2txt(num, base, NULL))
fputs("*ERROR*", stdout);
printf(". [%d]\n", fieldused);
}
}
return 0;
} /* main, testing */
#endif

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson

Nov 14 '05 #3
Understand the base system of the target type, and how to manipulate
it. Or, read the source code for a library function that implements it
or something simular.

Example (convert a byte value into hex string, untested):

char *str;
int i, len = 0, val = 19;

for(i=val; i /= 10; len++);

str = malloc(len + 1);
*str = len;

do {
*--str = (val % 10) + '0';
} while(val /= 10);

str[len + 1] = NUL;

whatluo wrote:
Hi, all

I'm now working on a program which will convert dec number to
hex and oct and bin respectively, I've checked the clc but with no
luck, so can anybody give me a hit how to make this done without
strtol or s/printf function.

Thanks,

whatluo.


Nov 14 '05 #4
Sorry I was too hasty in my reply.

W4CKO wrote:
Understand the base system of the target type, and how to manipulate
it. Or, read the source code for a library function that implements it
or something simular.

Example (convert a byte value into hex string, untested):

Rather, convert integer value into ascii string (an example of
manipulating base-10).
char *str;
int i, len = 0, val = 19;

for(i=val; i /= 10; len++);

str = malloc(len + 1);
*str = len;

do {
*--str = (val % 10) + '0';
} while(val /= 10);

str[len + 1] = NUL;

Let me put this in the form of a function (tested):

/* assumes buffer is adequate. */

#define NUL '\0'

char *int2str(char *buf, unsigned int val) {

unsigned int i, len = 0;

if(val == 0) return("0");

/* compute the length of the resultant string. */
for(i=val; i /= 10; len++);

/* start at the end of the buffer, */
*buf = len;

/* because we work backwards in the buffer. */
do {
*--buf = (val % 10) + '0';
} while(val /= 10);

buf[len + 1] = NUL;

return(buf);

}
whatluo wrote:
Hi, all

I'm now working on a program which will convert dec number to
hex and oct and bin respectively, I've checked the clc but with no
luck, so can anybody give me a hit how to make this done without
strtol or s/printf function.

Thanks,

whatluo.


Nov 14 '05 #5
W4CKO wrote:
Let me put this in the form of a function (tested):
Tested? Really!?
It only works right when val equals zero.
The function definition is very bad.
/* assumes buffer is adequate. */

#define NUL '\0'

char *int2str(char *buf, unsigned int val) {

unsigned int i, len = 0;

if(val == 0) return("0");
The interface is overly complicated.
Unless the return value is used directly,
it has to be stored in a separate variable.

/* compute the length of the resultant string. */
for(i=val; i /= 10; len++);
When val is 9, you get a length of zero.

/* start at the end of the buffer, */
*buf = len;
Writing a length to the first byte of buf, doesn't make sense.

/* because we work backwards in the buffer. */
do {
*--buf = (val % 10) + '0';
This takes you into memory you don't own,
because you didn't increment buf first.
That's a crasher.
} while(val /= 10);

buf[len + 1] = NUL;

return(buf);

}


That needed some work.

#include <stddef.h>

void int2str(char *buf, unsigned int val)
{
size_t i, len;

if (val == 0) {
*buf++ = '0';
*buf = '\0';
return;
}
/* compute the length of the resultant string. */
for (len = 1, i = val; (i /= 10) != 0; len++) {
;
}
/* start at the end of the buffer, */
buf += len;
*buf = '\0';
/* because we work backwards in the buffer. */
do {
*--buf = (char)(val % 10 + '0');
val /= 10;
} while(val != 0);
}

--
pete
Nov 14 '05 #6

"whatluo" <wh*****@gmail.com> wrote
I'm now working on a program which will convert dec number to
hex and oct and bin respectively, I've checked the clc but with no
luck, so can anybody give me a hit how to make this done without
strtol or s/printf function.

Convert to and from binary, i.e. the machine representation. That way you
need two functions for each base you support, instead of N-squared
conversions.

To convert from decimal to an integer, take the first digit, and convert
from an ASCII value to the number the character represents. The check is
there is another digit. If there is, multiply by ten, convert the next
digit, and add.

You can convert from all other number bases using similar logic.

Converting from an integer to an arbitrary base is not very efficient. You
need to take modulus ten for the last digit, divide by ten, take modulus ten
for the second to last digit, and so on. So a reverse string function is
very handy.

However when the base is a power of two, things are much easier.

1111 0010 in binary is
F 2 in hex.

As simple as that. So you can use the AND and OR operators with bitshifting
to convert without any divides.
Nov 14 '05 #7
Thanks everyone for the info, that's help me a lot, and I know how to
make it done, It's not a homework, just I'm writing a embeded module
which related to this.

Thanks,

huajian.

Nov 14 '05 #8

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

Similar topics

2
by: Peter Kwan | last post by:
Hi, I believe I have discovered a bug in Python 2.3. Could anyone suggest a get around? When I tested my existing Python code with the newly released Python 2.3, I get the following warning: ...
2
by: Phil Stanton | last post by:
When designing a new form or report, the Default ForeColor is often something like -2147483640 which is the colour of Windows text (possibly black) and the default backColor is -2147483643...
3
by: ET | last post by:
I don't know whats the problem, but after I added functions to first verify, then relink linked tables if not found, now I can't convert that database to MDE format. I can split the database, but...
30
by: ceeques | last post by:
Hi I am a novice in C. Could you guys help me solve this problem - I need to convert integer(and /short) to string without using sprintf (I dont have standard libray stdio.h). for...
4
by: dba_222 | last post by:
Dear Experts, Ok, I hate to ask such a seemingly dumb question, but I've already spent far too much time on this. More that I would care to admit. In Sql server, how do I simply change a...
1
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ 3.5. - How do I convert a Number into a String with exactly 2 decimal places?...
7
by: shellon | last post by:
Hi all: I want to convert the float number to sortable integer, like the function float2rawInt() in java, but I don't know the internal expression of float, appreciate your help!
19
by: VK | last post by:
http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/ b495b4898808fde0> is more than one month old - this may pose problem for posting over some news servers. This is why I'm...
28
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places?...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.