Related
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char * compress(char *input, int size){
char *inputa;
char compressedString[100];
inputa = (char*)malloc(sizeof(size));
snprintf (inputa, size, "%s", input);
int i = 0;
int x;
int counter;
while(i < size){
counter = 1;
x = i;
while (inputa[x] == inputa[x + 1] && (x+1) < size){
x++;
counter++;
}
if (i != x){
i = x;
}else{
i++;
}
}
return inputa;
}
main(){
char ez[] = "blaablaaa";
printf("%s \n", compress(ez, sizeof(ez)));
printf("%s", ez);
return 0;
}
So, I am trying to make this function that compresses consecutive characters (eg. "blaablaaa" to "bla2bla3"). My thought process is to put the inputa[x] on the compressed array and next to it the counter, but I can't seem to make it to work.
Lets take a look at these two lines:
inputa = (char*)malloc(sizeof(size));
snprintf (inputa, size, "%s", input);
size has type int, so sizeof(size) is the size of an integer, which is probably 4.
You used malloc to allocate 4 bytes.
Then you use snprintf to try to copy all of your input (blaablaaa, 10-bytes long) into a buffer that is only 4 bytes long.
10 bytes won't fit into a 4 byte buffer.
I'm not sure what you're trying to do there, but it is not correct.
1) Your allocated buffer was too short:
inputa = (char*)malloc(sizeof(size));
It allocates only 4 bytes.
You needed
inputa = (char*)malloc(sizeof(char)*size + 1 ));
2) You forgot to release the allocated memory.
3) The algorithm itself needed the improvements. Comments in the code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* itoa is not a standard function */
/* itoa: convert n to characters in s */
void itoa1(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
char * compress(char *input, int size){
int i = 0;
int r; // number of repetitions
char add[2]; // current character buffer
char rep[32]; // repetitions buffer
char c; // current character
char *compr = (char* )malloc(sizeof(char)*size + 1); // memory for the compressed string
compr[0] = 0; // terminate the buffer
add[1] = 0; // terminate the buffer
while(i < size){
c = add[0] = input[i]; // get a character
strcat(compr,add); // add to compr
r = 1; // default number of repetitions is one
while(1) // count and add to the string
{
if(c == input[i+1] )
{ // find how many characters follows c
r++; // number of repetition
i++; // moving along the input buffer
}
else
{
// check the r for number of repetitions
if( r > 1)
{
// there were repetitions:
// char * itoa ( int value, char * str, int base );
itoa1(r,rep); // get the number
strcat(compr,rep); // add repetition number to the compressed string
}
i++;// advance to the next character
break;
} // else
}// while
} //while
return compr;
}
int main(void){
char sg7[] = "BLaaaBBLLaaaaXXXaaY";
char ez[] = "blaablaaa";
char *ptr;
printf("%s \n", ptr = compress(sg7, strlen(sg7) ) );
printf("%s \n", sg7);
free(ptr);
printf("\n");
printf("%s \n", ptr = compress(ez, strlen(ez)));
printf("%s \n", ez);
free(ptr);
return 0;
}
Output:
BLa3B2L2a4X3a2Y
BLaaaBBLLaaaaXXXaaY
bla2bla3
blaablaaa
I hope it helps.
I am doing the easy challenge on /r/dailyprogrammer in C. I actually managed to write over a hundred lines of code, and spend a couple hours total on it (usually I end up chickening out), and figure out all the compiler errors. But now, when I run it, I immediately get a segfault. What I'm doing wrong?
Yes, it's sort of homework help, but at least I tried before coming here.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define MAXLEN 50
#define LIMIT 20
#define TRUE 1
#define FALSE 0
char* reverse(char *a);
char* ltoa(long i);
long atol(char *a); /* NOTE: Handle leading zeros. */
long palindromize(long p);
int ispalindrome(long p);
/* Meat. */
int main(int argc, char *argv[])
{
long p;
int count, limr;
p = (long) argv[1];
count = 0;
limr = FALSE;
while (TRUE)
{
p = palindromize(p);
count++;
if (ispalindrome(p))
{
break;
} else if (count == LIMIT) {
limr = TRUE;
break;
}
}
if (limr)
{
printf("It might be a palindrome, but it'd take quite a while to find out.\nLast number reached: %ld\n", p);
} else {
printf("Palindrome found! After %d steps, we've found %ld.\n", count, p);
}
}
long palindromize(long p)
{
return (atol(reverse(ltoa(p)))) + p;
}
int ispalindrome(long p)
{
char *t, *r;
t = ltoa(p);
r = reverse(ltoa(p));
if (t == r)
{
return TRUE;
} else {
return FALSE;
}
}
/* Utility functions. */
/* Converts string to long integer. */
long atol(char *a)
{
int i, sign;
long r;
for (i = 0; a[i] == '0'; i++)
{
i++;
}
if (a[0] == '-' || a[-1] == '-')
{
sign = -1;
}
else
{
sign = 1;
}
for (; isdigit(a[i]); i++)
{
r = 10 * r + (a[i] - '0');
}
return r * sign;
}
/* Converts long integer to string.
This and reverse are based on the ones in K&R. */
char* ltoa(long n)
{
char *a;
int i, sign;
if ((sign = n) < 0)
{
n = -n;
}
i = 0;
do
{
a[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0)
{
a[i++] = '-';
}
a[i] = '\0';
return reverse(a);
}
char* reverse(char *s)
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
return s;
}
In ltoa you declare char *a; but never malloc any space for it. When you access a[i] it crashes. For problems like this, remember a simple first debugging step is to add print statements everywhere so you can at least pinpoint where the error is occurring.
Looks like your ispalindrome is wrong too, but not in a seg fault way. I'll let you figure out why =D
char* ltoa(long n)
{
char *a;
int i, sign;
This is, in fact, a very common error. char *a is a pointer to a character (possibly a character array). But you don't tell it where the character are in memory. So it is pointing to some random location.
You can either reserve characters locally by using char a[100] or so, but that will land you with problems on returning from the function. Or you can reserve memory with char *a = (char *)malloc(100). Or you could consider palindromize the input string itself, and leave the memory problems to the caller.
Whenever I run my program, I think that I am getting the wrong output using the included test strings, though I think my first function is working. Tthe files I have are xbits.c xbits.h and two versions of showxbits.c, one that is instructor provided and the other is the one I am trying to use scanf with. The program is supposed to convert an integer to a hex string and then a hex string to an integer. My main problem is, while I think that my code works with the instructor test input, I know it doesn't work with the scanf showxbits because it gives answers such as 0xS when 127 is inputed.
Here is the xbits.c
#include <stdio.h>
#include <math.h>
int hex_To_dec(int c) {
char hex_values[] = "aAbBcCdDeEfF";
int i;
int answer = 0;
for (i=0; answer == 0 && hex_values[i] != '\0'; i++) {
if (hex_values[i] == c) {
answer = 10 + (i/2);
}
}
return answer;
}
/* function represents the int n as a hexstring which it places in the
hexstring array */
void itox(char* s, int n)
{
char *digits = "0123456789ABCDEF";
int i=0,j;
char temp;
while(n > 0)
{
s[i] = digits[n % 16];
n /= 16;
i++;
}
s[i] = '\0'; // Add null terminator
i--;
// Now reverse it in place
for(j=0; j < i / 2; j++)
{
temp = s[j];
s[j] = s[i - j];
s[i - j] = temp;
}
}
/* function converts hexstring array to equivalent integer value */
int xtoi(char hexstring[]) {
//printf("in xtoi, processing %s\n", hexstring);
int answer = 0;
int i = 0;
int valid = 1;
int hexit;
if (hexstring[i] == '0') {
++i;
if (hexstring[i] == 'x' || hexstring[i] == 'X') {
++i;
}
}
while(valid && hexstring[i] != '\0') {
answer = answer * 16;
if(hexstring[i] >='0' && hexstring[i] <= '9') {
answer = answer + (hexstring[i] - '0');
}
else {
hexit = hex_To_dec(hexstring[i]);
if (hexit == 0) {
valid = 0;
}
else {
answer = answer + hexit;
}
}
++i;
}
if(!valid) {
answer = 0;
}
return answer;
}
Here is the showxbits.c provided by the instructor:
/*
* stub driver for functions to study integer-hex conversions
*
*/
#include <stdio.h>
#include <string.h>
#include "xbits.h"
#define ENOUGH_SPACE 1000 /* not really enough space */
int main() {
char hexstring[ENOUGH_SPACE];
int m=0, n = 0x79FEB220;
itox(hexstring, n);
/* for stub testing: create a fake input string */
strcpy(hexstring, "6BCD7890");
m = xtoi(hexstring);
printf("\t%12d %s %12d\n", n, hexstring, m);
return 0; /* everything is just fine */
}
And here is the showxbits that has scanf in it:
/*
* stub driver for functions to study integer-hex conversions
*
*/
#include <stdio.h>
#include <string.h>
#include "xbits.h"
#define ENOUGH_SPACE 100 /* not really enough space */
int main() {
char hexstring[ENOUGH_SPACE];
//int m=0, n = 0x79FEB220;
int n, m;
while ((scanf("%d", &n)) == 1) {
itox(hexstring, n);
m = xtoi( hexstring);
printf("%12d %s %12d\n", n, hexstring, m);
}
return 0; /* everything is just fine */
}
Like I said, I am getting weird outputs when using the scanf function. I am a complete beginner programmer and would really appreciate any help that can be offered. Thanks!
Because there is a mistake in the function itox , which would cause the wrong result when reverse string. Then, the wrong hexstring from itox will result in the abnormal output finally.
The quick fix is to replace j < i / 2 with j < i / 2 + 1
void itox(char* s, int n)
{
//......
// Now reverse it in place
for(j=0; j < i / 2 + 1 ; j++)
{
temp = s[j];
s[j] = s[i - j];
s[i - j] = temp;
}
}
You don't need to reverse the string to convert to hex ascii:
#include <stdio.h>
const char* hexlat="0123456789ABCDEF";
char *binaryToHex(unsigned int answer, char *result){
if(answer==0) return result;
else{
result=binaryToHex(answer>>4,result);
*result=hexlat[answer & 0x0F];
return result+1;
}
};
int main(void) {
unsigned int answer=0x12340ADF;
char hexAnswer[32];
*binaryToHex(answer,hexAnswer)='\0';
printf("%s",hexAnswer);
return 0;
}
itoa() is a really handy function to convert a number to a string. Linux does not seem to have itoa(), is there an equivalent function or do I have to use sprintf(str, "%d", num)?
EDIT: Sorry, I should have remembered that this machine is decidedly non-standard, having plugged in various non-standard libc implementations for academic purposes ;-)
As itoa() is indeed non-standard, as mentioned by several helpful commenters, it is best to use sprintf(target_string,"%d",source_int) or (better yet, because it's safe from buffer overflows) snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int). I know it's not quite as concise or cool as itoa(), but at least you can Write Once, Run Everywhere (tm) ;-)
Here's the old (edited) answer
You are correct in stating that the default gcc libc does not include itoa(), like several other platforms, due to it not technically being a part of the standard. See here for a little more info. Note that you have to
#include <stdlib.h>
Of course you already know this, because you wanted to use itoa() on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:
Example
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}
Output:
Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110
itoa is not a standard C function. You can implement your own. It appeared in the first edition of Kernighan and Ritchie's The C Programming Language, on page 60. The second edition of The C Programming Language ("K&R2") contains the following implementation of itoa, on page 64. The book notes several issues with this implementation, including the fact that it does not correctly handle the most negative number
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
The function reverse used above is implemented two pages earlier:
#include <string.h>
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
If you are calling it a lot, the advice of "just use snprintf" can be annoying. So here's what you probably want:
const char *my_itoa_buf(char *buf, size_t len, int num)
{
static char loc_buf[sizeof(int) * CHAR_BITS]; /* not thread safe */
if (!buf)
{
buf = loc_buf;
len = sizeof(loc_buf);
}
if (snprintf(buf, len, "%d", num) == -1)
return ""; /* or whatever */
return buf;
}
const char *my_itoa(int num)
{ return my_itoa_buf(NULL, 0, num); }
Edit: I just found out about std::to_string which is identical in operation to my own function below. It was introduced in C++11 and is available in recent versions of gcc, at least as early as 4.5 if you enable the c++0x extensions.
Not only is itoa missing from gcc, it's not the handiest function to use since you need to feed it a buffer. I needed something that could be used in an expression so I came up with this:
std::string itos(int n)
{
const int max_size = std::numeric_limits<int>::digits10 + 1 /*sign*/ + 1 /*0-terminator*/;
char buffer[max_size] = {0};
sprintf(buffer, "%d", n);
return std::string(buffer);
}
Ordinarily it would be safer to use snprintf instead of sprintf but the buffer is carefully sized to be immune to overrun.
See an example: http://ideone.com/mKmZVE
As Matt J wrote, there is itoa, but it's not standard. Your code will be more portable if you use snprintf.
Following function allocates just enough memory to keep string representation of the given number and then writes the string representation into this area using standard sprintf method.
char *itoa(long n)
{
int len = n==0 ? 1 : floor(log10l(labs(n)))+1;
if (n<0) len++; // room for negative sign '-'
char *buf = calloc(sizeof(char), len+1); // +1 for null
snprintf(buf, len+1, "%ld", n);
return buf;
}
Don't forget to free up allocated memory when out of need:
char *num_str = itoa(123456789L);
// ...
free(num_str);
N.B. As snprintf copies n-1 bytes, we have to call snprintf(buf, len+1, "%ld", n) (not just snprintf(buf, len, "%ld", n))
Where is the itoa function in Linux?
There is no such function in Linux. I use this code instead.
/*
=============
itoa
Convert integer to string
PARAMS:
- value A 64-bit number to convert
- str Destination buffer; should be 66 characters long for radix2, 24 - radix8, 22 - radix10, 18 - radix16.
- radix Radix must be in range -36 .. 36. Negative values used for signed numbers.
=============
*/
char* itoa (unsigned long long value, char str[], int radix)
{
char buf [66];
char* dest = buf + sizeof(buf);
boolean sign = false;
if (value == 0) {
memcpy (str, "0", 2);
return str;
}
if (radix < 0) {
radix = -radix;
if ( (long long) value < 0) {
value = -value;
sign = true;
}
}
*--dest = '\0';
switch (radix)
{
case 16:
while (value) {
* --dest = '0' + (value & 0xF);
if (*dest > '9') *dest += 'A' - '9' - 1;
value >>= 4;
}
break;
case 10:
while (value) {
*--dest = '0' + (value % 10);
value /= 10;
}
break;
case 8:
while (value) {
*--dest = '0' + (value & 7);
value >>= 3;
}
break;
case 2:
while (value) {
*--dest = '0' + (value & 1);
value >>= 1;
}
break;
default: // The slow version, but universal
while (value) {
*--dest = '0' + (value % radix);
if (*dest > '9') *dest += 'A' - '9' - 1;
value /= radix;
}
break;
}
if (sign) *--dest = '-';
memcpy (str, dest, buf +sizeof(buf) - dest);
return str;
}
Reading the code of guys who do it for a living will get you a LONG WAY.
Check out how guys from MySQL did it. The source is VERY WELL COMMENTED and will teach you much more than hacked up solutions found all over the place.
MySQL's implementation of int2str
I provide the mentioned implementation here; the link is here for reference and should be used to read the full implementation.
char *
int2str(long int val, char *dst, int radix,
int upcase)
{
char buffer[65];
char *p;
long int new_val;
char *dig_vec= upcase ? _dig_vec_upper : _dig_vec_lower;
ulong uval= (ulong) val;
if (radix < 0)
{
if (radix < -36 || radix > -2)
return NullS;
if (val < 0)
{
*dst++ = '-';
/* Avoid integer overflow in (-val) for LLONG_MIN (BUG#31799). */
uval = (ulong)0 - uval;
}
radix = -radix;
}
else if (radix > 36 || radix < 2)
return NullS;
/*
The slightly contorted code which follows is due to the fact that
few machines directly support unsigned long / and %. Certainly
the VAX C compiler generates a subroutine call. In the interests
of efficiency (hollow laugh) I let this happen for the first digit
only; after that "val" will be in range so that signed integer
division will do. Sorry 'bout that. CHECK THE CODE PRODUCED BY
YOUR C COMPILER. The first % and / should be unsigned, the second
% and / signed, but C compilers tend to be extraordinarily
sensitive to minor details of style. This works on a VAX, that's
all I claim for it.
*/
p = &buffer[sizeof(buffer)-1];
*p = '\0';
new_val= uval / (ulong) radix;
*--p = dig_vec[(uchar) (uval- (ulong) new_val*(ulong) radix)];
val = new_val;
while (val != 0)
{
ldiv_t res;
res=ldiv(val,radix);
*--p = dig_vec[res.rem];
val= res.quot;
}
while ((*dst++ = *p++) != 0) ;
return dst-1;
}
i tried my own implementation of itoa(), it seem's work in binary, octal, decimal and hex
#define INT_LEN (10)
#define HEX_LEN (8)
#define BIN_LEN (32)
#define OCT_LEN (11)
static char * my_itoa ( int value, char * str, int base )
{
int i,n =2,tmp;
char buf[BIN_LEN+1];
switch(base)
{
case 16:
for(i = 0;i<HEX_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%x" ,value);
break;
case 10:
for(i = 0;i<INT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%d" ,value);
break;
case 8:
for(i = 0;i<OCT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%o" ,value);
break;
case 2:
for(i = 0,tmp = value;i<BIN_LEN;++i)
{
if(tmp/base>0)
{
n++;
}
tmp/=base;
}
for(i = 1 ,tmp = value; i<n;++i)
{
if(tmp%2 != 0)
{
buf[n-i-1] ='1';
}
else
{
buf[n-i-1] ='0';
}
tmp/=base;
}
buf[n-1] = '\0';
strcpy(str,buf);
break;
default:
return NULL;
}
return str;
}
direct copy to buffer : 64 bit integer itoa hex :
char* itoah(long num, char* s, int len)
{
long n, m = 16;
int i = 16+2;
int shift = 'a'- ('9'+1);
if(!s || len < 1)
return 0;
n = num < 0 ? -1 : 1;
n = n * num;
len = len > i ? i : len;
i = len < i ? len : i;
s[i-1] = 0;
i--;
if(!num)
{
if(len < 2)
return &s[i];
s[i-1]='0';
return &s[i-1];
}
while(i && n)
{
s[i-1] = n % m + '0';
if (s[i-1] > '9')
s[i-1] += shift ;
n = n/m;
i--;
}
if(num < 0)
{
if(i)
{
s[i-1] = '-';
i--;
}
}
return &s[i];
}
note: change long to long long for 32 bit machine. long to int in case for 32 bit integer. m is the radix. When decreasing radix, increase number of characters (variable i). When increasing radix, decrease number of characters (better). In case of unsigned data type, i just becomes 16 + 1.
Here is a much improved version of Archana's solution. It works for any radix 1-16, and numbers <= 0, and it shouldn't clobber memory.
static char _numberSystem[] = "0123456789ABCDEF";
static char _twosComp[] = "FEDCBA9876543210";
static void safestrrev(char *buffer, const int bufferSize, const int strlen)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
for (int index = 0; index < (len / 2); index++)
{
char ch = buffer[index];
buffer[index] = buffer[len - index - 1];
buffer[len - index - 1] = ch;
}
}
static int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
if (radix == 10)
{
if (len < (bufferSize - 1))
{
buffer[len++] = '-';
buffer[len] = '\0';
}
}
else
{
int twosCompIndex = 0;
for (int index = 0; index < len; index++)
{
if ((buffer[index] >= '0') && (buffer[index] <= '9'))
{
twosCompIndex = buffer[index] - '0';
}
else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))
{
twosCompIndex = buffer[index] - 'A' + 10;
}
else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))
{
twosCompIndex = buffer[index] - 'a' + 10;
}
twosCompIndex += (16 - radix);
buffer[index] = _twosComp[twosCompIndex];
}
if (len < (bufferSize - 1))
{
buffer[len++] = _numberSystem[radix - 1];
buffer[len] = 0;
}
}
return len;
}
static int twosNegation(const int x, const int radix)
{
int n = x;
if (x < 0)
{
if (radix == 10)
{
n = -x;
}
else
{
n = ~x;
}
}
return n;
}
static char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)
{
int strlen = 0;
int n = twosNegation(x, radix);
int nuberSystemIndex = 0;
if (radix <= 16)
{
do
{
if (strlen < (bufferSize - 1))
{
nuberSystemIndex = (n % radix);
buffer[strlen++] = _numberSystem[nuberSystemIndex];
buffer[strlen] = '\0';
n = n / radix;
}
else
{
break;
}
} while (n != 0);
if (x < 0)
{
strlen = negateBuffer(buffer, bufferSize, strlen, radix);
}
safestrrev(buffer, bufferSize, strlen);
return buffer;
}
return NULL;
}
Where is the itoa function in Linux?
As itoa() is not standard in C, various versions with various function signatures exists.
char *itoa(int value, char *str, int base); is common in *nix.
Should it be missing from Linux or if code does not want to limit portability, code could make it own.
Below is a version that does not have trouble with INT_MIN and handles problem buffers: NULL or an insufficient buffer returns NULL.
#include <stdlib.h>
#include <limits.h>
#include <string.h>
// Buffer sized for a decimal string of a `signed int`, 28/93 > log10(2)
#define SIGNED_PRINT_SIZE(object) ((sizeof(object) * CHAR_BIT - 1)* 28 / 93 + 3)
char *itoa_x(int number, char *dest, size_t dest_size) {
if (dest == NULL) {
return NULL;
}
char buf[SIGNED_PRINT_SIZE(number)];
char *p = &buf[sizeof buf - 1];
// Work with negative absolute value
int neg_num = number < 0 ? number : -number;
// Form string
*p = '\0';
do {
*--p = (char) ('0' - neg_num % 10);
neg_num /= 10;
} while (neg_num);
if (number < 0) {
*--p = '-';
}
// Copy string
size_t src_size = (size_t) (&buf[sizeof buf] - p);
if (src_size > dest_size) {
// Not enough room
return NULL;
}
return memcpy(dest, p, src_size);
}
Below is a C99 or later version that handles any base [2...36]
char *itoa_x(int number, char *dest, size_t dest_size, int base) {
if (dest == NULL || base < 2 || base > 36) {
return NULL;
}
char buf[sizeof number * CHAR_BIT + 2]; // worst case: itoa(INT_MIN,,,2)
char *p = &buf[sizeof buf - 1];
// Work with negative absolute value to avoid UB of `abs(INT_MIN)`
int neg_num = number < 0 ? number : -number;
// Form string
*p = '\0';
do {
*--p = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[-(neg_num % base)];
neg_num /= base;
} while (neg_num);
if (number < 0) {
*--p = '-';
}
// Copy string
size_t src_size = (size_t) (&buf[sizeof buf] - p);
if (src_size > dest_size) {
// Not enough room
return NULL;
}
return memcpy(dest, p, src_size);
}
For a C89 and onward compliant code, replace inner loop with
div_t qr;
do {
qr = div(neg_num, base);
*--p = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[-qr.rem];
neg_num = qr.quot;
} while (neg_num);
glibc internal implementation
glibc 2.28 has an internal implementation:
stdio-common/_itoa.c
sysdeps/generic/_itoa.h
which is used in several places internally, but I could not find if it can be exposed or how.
At least that should be a robust implementation if you are willing to extract it.
This question asks how to roll your own: How to convert an int to string in C?
I would prefer this: https://github.com/wsq003/itoa_for_linux
It should be the fastest itoa() ever. We use itoa() instead of sprintf() for performance reason, so a fastest itoa() with limited feature is reasonable and worthwhile.
If you just want to print them:
void binary(unsigned int n)
{
for(int shift=sizeof(int)*8-1;shift>=0;shift--)
{
if (n >> shift & 1)
printf("1");
else
printf("0");
}
printf("\n");
}
The replacement with snprintf is NOT complete!
It covers only bases: 2, 8, 10, 16, whereas itoa works for bases between 2 and 36.
Since I was searching a replacement for base 32, I guess I'll have to code my own!
I have used _itoa(...) on RedHat 6 and GCC compiler. It works.
You can use this program instead of sprintf.
void itochar(int x, char *buffer, int radix);
int main()
{
char buffer[10];
itochar(725, buffer, 10);
printf ("\n %s \n", buffer);
return 0;
}
void itochar(int x, char *buffer, int radix)
{
int i = 0 , n,s;
n = s;
while (n > 0)
{
s = n%radix;
n = n/radix;
buffer[i++] = '0' + s;
}
buffer[i] = '\0';
strrev(buffer);
}
I recently read a sample job interview question:
Write a function to convert an integer
to a string. Assume you do not have
access to library functions i.e.,
itoa(), etc...
How would you go about this?
fast stab at it: (edited to handle negative numbers)
int n = INT_MIN;
char buffer[50];
int i = 0;
bool isNeg = n<0;
unsigned int n1 = isNeg ? -n : n;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf(buffer);
A look on the web for itoa implementation will give you good examples. Here is one, avoiding to reverse the string at the end. It relies on a static buffer, so take care if you reuse it for different values.
char* itoa(int val, int base){
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base)
buf[i] = "0123456789abcdef"[val % base];
return &buf[i+1];
}
The algorithm is easy to see in English.
Given an integer, e.g. 123
divide by 10 => 123/10. Yielding, result = 12 and remainder = 3
add 30h to 3 and push on stack (adding 30h will convert 3 to ASCII representation)
repeat step 1 until result < 10
add 30h to result and store on stack
the stack contains the number in order of | 1 | 2 | 3 | ...
I would keep in mind that all of the digit characters are in increasing order within the ASCII character set and do not have other characters between them.
I would also use the / and the% operators repeatedly.
How I would go about getting the memory for the string would depend on information you have not given.
Assuming it is in decimal, then like this:
int num = ...;
char res[MaxDigitCount];
int len = 0;
for(; num > 0; ++len)
{
res[len] = num%10+'0';
num/=10;
}
res[len] = 0; //null-terminating
//now we need to reverse res
for(int i = 0; i < len/2; ++i)
{
char c = res[i]; res[i] = res[len-i-1]; res[len-i-1] = c;
}
An implementation of itoa() function seems like an easy task but actually you have to take care of many aspects that are related on your exact needs. I guess that in the interview you are expected to give some details about your way to the solution rather than copying a solution that can be found in Google (http://en.wikipedia.org/wiki/Itoa)
Here are some questions you may want to ask yourself or the interviewer:
Where should the string be located (malloced? passed by the user? static variable?)
Should I support signed numbers?
Should i support floating point?
Should I support other bases rather then 10?
Do we need any input checking?
Is the output string limited in legth?
And so on.
Convert integer to string without access to libraries
Convert the least significant digit to a character first and then proceed to more significant digits.
Normally I'd shift the resulting string into place, yet recursion allows skipping that step with some tight code.
Using neg_a in myitoa_helper() avoids undefined behavior with INT_MIN.
// Return character one past end of character digits.
static char *myitoa_helper(char *dest, int neg_a) {
if (neg_a <= -10) {
dest = myitoa_helper(dest, neg_a / 10);
}
*dest = (char) ('0' - neg_a % 10);
return dest + 1;
}
char *myitoa(char *dest, int a) {
if (a >= 0) {
*myitoa_helper(dest, -a) = '\0';
} else {
*dest = '-';
*myitoa_helper(dest + 1, a) = '\0';
}
return dest;
}
void myitoa_test(int a) {
char s[100];
memset(s, 'x', sizeof s);
printf("%11d <%s>\n", a, myitoa(s, a));
}
Test code & output
#include "limits.h"
#include "stdio.h"
int main(void) {
const int a[] = {INT_MIN, INT_MIN + 1, -42, -1, 0, 1, 2, 9, 10, 99, 100,
INT_MAX - 1, INT_MAX};
for (unsigned i = 0; i < sizeof a / sizeof a[0]; i++) {
myitoa_test(a[i]);
}
return 0;
}
-2147483648 <-2147483648>
-2147483647 <-2147483647>
-42 <-42>
-1 <-1>
0 <0>
1 <1>
2 <2>
9 <9>
10 <10>
99 <99>
100 <100>
2147483646 <2147483646>
2147483647 <2147483647>
The faster the better?
unsigned countDigits(long long x)
{
int i = 1;
while ((x /= 10) && ++i);
return i;
}
unsigned getNumDigits(long long x)
{
x < 0 ? x = -x : 0;
return
x < 10 ? 1 :
x < 100 ? 2 :
x < 1000 ? 3 :
x < 10000 ? 4 :
x < 100000 ? 5 :
x < 1000000 ? 6 :
x < 10000000 ? 7 :
x < 100000000 ? 8 :
x < 1000000000 ? 9 :
x < 10000000000 ? 10 : countDigits(x);
}
#define tochar(x) '0' + x
void tostr(char* dest, long long x)
{
unsigned i = getNumDigits(x);
char negative = x < 0;
if (negative && (*dest = '-') & (x = -x) & i++);
*(dest + i) = 0;
while ((i > negative) && (*(dest + (--i)) = tochar(((x) % 10))) | (x /= 10));
}
If you want to debug, You can split the conditions (instructions) into
lines of code inside the while scopes {}.
I came across this question so I decided to drop by the code I usually use for this:
char *SignedIntToStr(char *Dest, signed int Number, register unsigned char Base) {
if (Base < 2 || Base > 36) {
return (char *)0;
}
register unsigned char Digits = 1;
register unsigned int CurrentPlaceValue = 1;
for (register unsigned int T = Number/Base; T; T /= Base) {
CurrentPlaceValue *= Base;
Digits++;
}
if (!Dest) {
Dest = malloc(Digits+(Number < 0)+1);
}
char *const RDest = Dest;
if (Number < 0) {
Number = -Number;
*Dest = '-';
Dest++;
}
for (register unsigned char i = 0; i < Digits; i++) {
register unsigned char Digit = (Number/CurrentPlaceValue);
Dest[i] = (Digit < 10? '0' : 87)+Digit;
Number %= CurrentPlaceValue;
CurrentPlaceValue /= Base;
}
Dest[Digits] = '\0';
return RDest;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
char String[32];
puts(SignedIntToStr(String, -100, 16));
return 0;
}
This will automatically allocate memory if NULL is passed into Dest. Otherwise it will write to Dest.
Here's a simple approach, but I suspect if you turn this in as-is without understanding and paraphrasing it, your teacher will know you just copied off the net:
char *pru(unsigned x, char *eob)
{
do { *--eob = x%10; } while (x/=10);
return eob;
}
char *pri(int x, char *eob)
{
eob = fmtu(x<0?-x:x, eob);
if (x<0) *--eob='-';
return eob;
}
Various improvements are possible, especially if you want to efficiently support larger-than-word integer sizes up to intmax_t. I'll leave it to you to figure out the way these functions are intended to be called.
Slightly longer than the solution:
static char*
itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
return s;
}
Reverse:
int strlen(const char* str)
{
int i = 0;
while (str != '\0')
{
i++;
str++;
}
return i;
}
static void
reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
And although the decision davolno long here are some useful features for beginners. I hope you will be helpful.
This is the shortest function I can think of that:
Correctly handles all signed 32-bit integers including 0, MIN_INT32, MAX_INT32.
Returns a value that can be printed immediatelly, e.g.: printf("%s\n", GetDigits(-123))
Please comment for improvements:
static const char LARGEST_NEGATIVE[] = "-2147483648";
static char* GetDigits(int32_t x) {
char* buffer = (char*) calloc(sizeof(LARGEST_NEGATIVE), 1);
int negative = x < 0;
if (negative) {
if (x + (1 << 31) == 0) { // if x is the largest negative number
memcpy(buffer, LARGEST_NEGATIVE, sizeof(LARGEST_NEGATIVE));
return buffer;
}
x *= -1;
}
// storing digits in reversed order
int length = 0;
do {
buffer[length++] = x % 10 + '0';
x /= 10;
} while (x > 0);
if (negative) {
buffer[length++] = '-'; // appending minus
}
// reversing digits
for (int i = 0; i < length / 2; i++) {
char temp = buffer[i];
buffer[i] = buffer[length-1 - i];
buffer[length-1 - i] = temp;
}
return buffer;
}
//Fixed the answer from [10]
#include <iostream>
void CovertIntToString(unsigned int n1)
{
unsigned int n = INT_MIN;
char buffer[50];
int i = 0;
n = n1;
bool isNeg = n<0;
n1 = isNeg ? -n1 : n1;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
// Now we must reverse the string
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf("%s", buffer);
}
int main() {
unsigned int x = 4156;
CovertIntToString(x);
return 0;
}
This function converts each digits of number into a char and chars add together
in one stack forming a string. Finally, string is formed from integer.
string convertToString(int num){
string str="";
for(; num>0;){
str+=(num%10+'0');
num/=10;
}
return str;
}