I want to write C Code which converts first string into integer then integer into hexadecimal.
ex: I have Ip iddress as "172.24.18.240" now first find out first dot from it and take the number before it that is "172" convert it into integer then convert it inti hexadecimal and it should do the same for all like 24,18,240 and convert into long/integer value
any help is appreciated.
#include <stdio.h> // testing
int main(int argc, char** argv) // testing
{
char* ipString = argc > 1? argv[1] : "172.24.18.240"; // testing
char* ip = ipString;
unsigned int hex;
for( int i = 0; i < 4; i++ ){
unsigned int n = 0;
for( char c; (c = *ip) >= '0' && c <= '9'; ip++ )
n = 10 * n + c - '0';
hex = (hex << 8) + n;
if( *ip == '.' ) ip++;
}
printf("%08X\n", hex); // testing
return 0; // testing
}
Maybe something like this?
char sn[4];
char *nid = hexString;
int nip[4];
int xnip[4];
int j = 0;
while (*nid != '\0') {
int i = 0;
memset(sn, '\0', sizeof sn);
while (isdigit(*nid)) {
sn[i++] = *nid++;
}
if (*nid == '.')
nid++;
// now sn should be the number part
nip[j] = your_str_to_int(sn);
xnip[j] = your_int_to_hex(nip[j]);
j++;
}
int main(void)
{
char hexChars[] = "0123456789ABCDEF";
char ipString[] = "172.24.18.254";
char hexString[9] = "";
const char* pch = ipString;
int num = 0;
int i = 0;
do
{
if (*pch != '.' && *pch != '\0')
{
num *= 10;
num += (*pch - '0');
}
else
{
hexString[i++] = hexChars[num / 16];
hexString[i++] = hexChars[num % 16];
num = 0;
}
} while (*pch++);
return 0;
}
The hex values will stored in hexString.
int i = 0, sum = 0;
char ipString[] = "172.24.18.240";
do
{
if (isdigit(ipString[i])) sum = sum * 10 + ipString[i] - '0';
else
{ putchar("0123456789ABCDEF"[sum / 16]);
putchar("0123456789ABCDEF"[sum % 16]);
putchar('.');
sum = 0;
}
}
while (ipString[i++] != '\0');
More or less ugly, but should work on IP addresses.
Related
I'm trying to create a function that converts an integer into a string, basically what have I done is the following functions: when we get the numbers from the conversion they are reversed so I need a reverse function to make them in the right way. The intostring uses (I think? I got it from some website) the ascii table to convert the number into the string desired.
The problem is: when I enter the 2-digit number they are reversed the wrong way (I guess my reverse function doesn't work that well) and after a certain number of digit the conversion it's not any more accurate.
reverse function:
char reverse(char *stringa) {
int len = strlen(stringa) - 1;
for(int i = 0; i < len / 2; i++) {
char tmp = stringa[i];
stringa[i] = stringa[len - i];
stringa[len - i] = tmp;
}
}
intostring function:
void intostring(int num, char *str) {
int i = 0;
while (num != 0) {
int rem = num % 10;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num / 10;
}
str[i] = '\0';
reverse(str);
}
The condition i<len/2 in the reverse function is wrong.
For example, if the string is 2-digit long, len will be 1 and len/2 will be 0. Therefore, no swap will occure while the two characters should be swapped.
the condition should be i<=len/2 or i<len-i.
/*
It works clearly . Checked.
*/
void reverse(char source[],char destination[]) {
int x,i;
//start from last char
i = i=(strlen(source)-1
for (x=0;x<strlen(source);x++){
//Insert char at i in source to x in destination
destination[x]=source[i];
destination[x]='\0';
i--;
}
}
There are multiple problems:
the reverse function fails for an empty string. You should not subtract 1 from the length, but adjust the offset inside the loop.
reverse is defined to return a char but does not return anything. Make it return a char * and return stringa.
intostring produces an empty string for num <= 0. You should loop while num > 9 and add the final digit after the loop.
intostring converts the digit into a character for bases up to 36 (assuming ASCII). This is unnecessarily complex since the base is 10. Use a simpler conversion: str[i++] = '0' + rem;
it may be useful for intostring to return a pointer to the destination array.
Here is a modified version:
#include <string.h>
char *reverse(char *str) {
size_t len = strlen(str);
for (size_t i = 0; i < len / 2; i++) {
char tmp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = tmp;
}
return str;
}
char *intostring(int num, char *str) {
int i = 0;
if (num >= 0) {
while (num > 9) {
str[i++] = '0' + num % 10;
num = num / 10;
}
str[i++] = '0' + num;
} else {
while (num < -9) {
str[i++] = '0' - num % 10;
num = num / 10;
}
str[i++] = '0' - num;
str[i++] = '-';
}
str[i] = '\0';
return reverse(str);
}
Here is an alternative approach for the reverse function using 2 index variables:
#include <string.h>
char *reverse(char *str) {
size_t i = 0;
size_t j = strlen(str);
while (j --> i) {
char c = str[j];
str[j] = str[i];
str[i++] = c;
}
return str;
}
The reverse function condition is worng.
If the integer in 32 then the string will be
s[0] = '2', s[1] = '3', s[2] = '\0' before string reversal.
so in reverse function the following swap operation has to be applied as
if number = 32 then len = 2
i = 0 then len - i - 1 = 1
so 0 and 1 will be swaped.
void reverse(char *stringa){
int len = strlen(stringa);
for(int i = 0; i < len / 2; i++){
char tmp = stringa[i];
stringa[i] = stringa[len - i - 1];
stringa[len - i - 1] = tmp;
}
}
void intostring(int num, char *str)
{
int i = 0;
if(num == 0){
str[i++] = '0';
str[i] = '\0';
}
else if(num > 0){
while(num != 0){
int rem = num % 10;
str[i++] = '0' + rem;
num = num/10;
}
str[i] = '\0';
}
else{
while(num != 0){
int rem = num % 10;
/*
(-5/2) => -2
-2 * 2 => -4
so a%b => -1
(5/-2) => -2
-2 * -2 => 4
so a%b => 1
*/
rem = abs(rem); // as the rem value is negative
str[i++] = '0' + rem;
num = num/10;
}
str[i++] = '-';
str[i] = '\0';
}
reverse(str);
}
Your reverse function is wrong. You can make it correct (and readable) like below:
void reverse(char *stringa) {
int i = 0; //Forwarding moving index
int j = strlen(stringa) - 1; // the end index
int tmp; // Edited to get the code compiled
for (; i < j; i++, j--) {
tmp = stringa[i];
stringa[i] = stringa[j];
stringa[j] = tmp;
}
}
Got to transform a binary number to decimal for recoding printf (no lib or functions allowed except malloc and write). i'm doing my calculs on char *, so it can't overflow. But when i hit a certain size, my result differ from a online binary converter, and i noticed that the binary converter keep always only 20 digits.
for exemple :
binary : 1.11111111111111111111111111
binary converter = 1.99999998509883880615,
my o converter == 1.99799896499882880605234375,
I guess the online converter keep the result rounded in an unsigned long long, but i don't understand how this rounding is calculated.
Do you have any clues?
Here is my code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char *ft_binary_pow(char *tmp, int i)
{
int j;
int div;
int remnant;
j = 0;
remnant = 0;
tmp[0] = '1';
tmp.sign = 0;
while (i > 0)
{
while (isdigit(tmp[j]) || remnant != 0)
{
if (tmp[j])
div = ((tmp[j] - '0') * 10) / 2;
else
div = 0;
tmp[j] = ((div / 10) + remnant) + '0';
remnant = div % 10;
j++;
}
j = 0;
i--;
}
return (tmp);
}
char *ft_add_tmp(char *ret, char *tmp)
{
int i;
int j;
int add;
int remnant;
i = strlen(tmp);
add = 0;
remnant = 0;
while (--i >= 0)
{
if (!ret[i])
add = tmp[i] - '0';
else
add = (ret[i] - '0') + (tmp[i] - '0');
if ((add % 10 + remnant) < 10)
ret[i] = (add % 10 + remnant) + '0';
else
ret[i] = '0';
remnant = add / 10 ? 1 : 0;
}
return (ret);
}
int main(void)
{
int i;
char *lol = "11111111111111111111111111";
char *ret;
char *tmp;
if (!(ret = (char *)calloc(340, sizeof(char))))
return (0);
i = 0;
ret[0] = '1';
while (lol[i])
{
if (lol[i] == '1')
{
if (!(tmp = (char *)calloc(50, sizeof(char))))
return (0);
tmp = ft_binary_pow(tmp, i + 1);
ret = ft_add_tmp(ret, tmp);
free(tmp);
}
i++;
}
printf("ret = %s\n", ret);
return (0);
}
Edited for more readable code
Thanks for your time!
Code fails even with lol = "111111111".
Code fails in ft_add_tmp() to handle a carry (overflow) into the next most significant digit.
else {
ret.decimal[i] = '0';
// add something like this and then also prorogate carry as needed to higher digits
ret.decimal[i-1]++;
}
Suggested correction and simplification:
char* ft_add_tmp(char *ret, const char *tmp) {
size_t i = strlen(tmp);
unsigned carry = 0;
while (i-- > 0) {
unsigned sum = ret[i] ? ret[i] - '0' : 0;
sum += tmp[i] - '0' + carry;
ret[i] = sum % 10 + '0';
carry = sum / 10;
}
assert(carry == 0);
return (ret);
}
This code is supposed to take a user's input and convert it to binary. The input is grouped into an integer array to store character codes and/or adjacent digits, then each item in the integer array is converted to binary. When the user types "c357", "c" should be converted to 99, then converted to binary. Then, "357" should be converted to binary as well. In the main() function, strlen(convert) does not accurately represent the number of items in array convert, thus only iterating over the first array item.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
return l;
}
// CONVERT INPUT TO BINARY VALUE
char* convertToBinary(unsigned long int decimal) {
int l = getBitLength(decimal);
static char b[33];
char bin[33];
int i, j, k = 0, r;
b[33] = '\0';
bin[33] = '\0';
printf("Bits................ %ld\n", l);
// creates array
for (i = 0; i < l; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
for (j = l - 1; j >= 0; j--) {
bin[k] = b[j];
strncpy(&bin[k], &b[j], l);
snprintf(&bin[k], l, "%d", b[j]);
k++;
}
printf("Binary Value: %s\n", bin);
return bin;
}
unsigned long int* numbersToConvert(char* input) {
const int MAX_INPUT = 20;
int i, k = 0, z = 0;
char numbers[MAX_INPUT];
unsigned long int *toConvert = malloc(MAX_INPUT * sizeof(int));
numbers[MAX_INPUT] = '\0';
for (i = 0; i < strlen(input); i++) {
if (isdigit(input[i])) {
numbers[z] = input[i];
if (!isdigit(input[i + 1])) {
toConvert[k] = strtol(numbers, NULL, 10);
printf("----- %ld -----\n", toConvert[k]);
z = 0;
}
else {
z++;
}
}
else {
printf("----- %c -----\n", input[i]);
printf("Character Code: %d\n", input[i]);
toConvert[k] = (unsigned long int) input[i];
}
k++;
}
return toConvert;
}
int main(void) {
const int MAX_INPUT = 20;
int i, p;
char input[MAX_INPUT];
unsigned long int* convert;
printf("------- Input --------\n");
scanf("%s", input);
input[MAX_INPUT] = '\0';
// PRINT INPUT AND SIZE
printf("\nInput: %s\n", input);
convert = numbersToConvert(input);
convert[MAX_INPUT] = '\0';
printf("strlen: %ld\n", strlen(convert));
for (i = 0; i < strlen(convert); i++) {
printf("num array: %ld\n", convert[i]);
convertToBinary(convert[i]);
}
return 0;
}
I have attempted to null terminate each string to prevent undefined behavior. I am unsure if certain variables, if any, are meant to be static.
It is hard to read your code.
Here you have something working (converting the number to binary):
static char *reverse(char *str)
{
char *end = str + strlen(str) - 1;
char *saved = str;
int ch;
while(end > str)
{
ch = *end;
*end-- = *str;
*str++ = ch;
}
return saved;
}
char *tostr(char *buff, unsigned long long val)
{
if(buff)
{
char *cpos = buff;
while(val)
{
*cpos++ = (val & 1) + '0';
val >>= 1;
}
*cpos = 0;
reverse(buff);
}
return buff;
}
int main()
{
char buff[128];
printf("%s\n", tostr(buff, 128));
}
https://godbolt.org/z/6sRC4C
If I had two strings:
a = "1234"
b = "4321"
I could add the two numbers together like this:
for(i=0; i<width-1; i++){
sum = (a[width-2-i]-48) + (b[width-2-i]-48) + carry;
carry = 0;
if(sum > 9){
carry = 1;
sum-=10;
}
answer[i] = sum+48;
}
if(carry) answer[i++] = carry+48;
answer[i]= 0;
And then reverse it (width is equal to strlen(a)).
How could I do the same thing if the following?
a = "12345"
b = "4321"
Would I need to reallocate memory? Or what?
(BTW - the problem I'm trying to solve is using many numbers all with 50 digits, so strtoul or strtoull is out of the question as I understand. Here's my code so far.)
int getcharval(const char *s, int idx) {
if (idx < strlen(s))
return s[strlen(s) - idx - 1] - 48;
return 0;
}
void add() {
const char *a = "1234";
const char *b = "13210";
char answer[256];
int i, wa=strlen(a), wb=strlen(b), width, sum, carry;
width = wa > wb ? wa : wb;
for(i=0; i<width; i++){
char ca = getcharval(a, i);
char cb = getcharval(b, i);
printf("%d %d\n", ca, cb);
sum = ca + cb + carry;
carry = 0;
if(sum > 9){
carry = 1;
sum-=10;
}
answer[i] = sum+48;
}
if(carry) answer[i++] = carry+48;
answer[i]= 0;
for (i = 0; i < strlen(answer) / 2; i++) {
char t = answer[i];
answer[i] = answer[strlen(answer) - i - 1];
answer[strlen(answer) - i - 1] = t;
}
printf("%s\n", answer);
}
If you insist on using the "elementary school addition", find the length of both strings, advance to their ends, and then move back until the shorter string's length is exhausted. Then continue moving in only the longer string, assuming that the remaining digits of the shorter string are zeros:
12345
04321
You need to move all the way to the beginning of the longer string, and process the carry there. Note that you need to allocate a new result anyway, because adding two N-digit numbers may result in a N+1-digit number due to the carry.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define c2d(c) (c-'0')
#define d2c(c) (c+'0')
char* add(const char *a, const char *b, char *ans){
int alen, blen;
int i, carry=0;
char *wk;
char *awk=strdup(a);
char *bwk=strdup(b);
alen=strlen(strrev(awk));
blen=strlen(strrev(bwk));
if(alen<blen){
alen ^= blen;blen ^= alen;alen ^= blen;//swap
wk = awk ; awk = bwk ; bwk = wk;
}
ans[alen+1]=ans[alen]='\0';
for(i=0;i<alen;++i){
int sum = c2d(awk[i])+(i<blen ? c2d(bwk[i]): 0)+carry;
ans[i] = d2c(sum % 10);
carry = sum / 10;
}
if(carry){
ans[i++]='1';
}
free(awk);
free(bwk);
return strrev(ans);
}
int main(){
const char *a="12345";
const char *b="4321";
char ans[6];
printf("{%s}+{%s}={%s}\n", a, b, add(a,b, ans));
return 0;
}
cited from C - Adding the numbers in 2 strings together if a different length
answer, I write a more readable codeļ¼
void str_reverse(char *beg, char *end){
if(!beg || !end)return;
char cTmp;
while(beg < end){
cTmp = *beg;
*beg++ = *end;
*end-- = cTmp;
}
}
#define c2d(c) (c - '0')
#define d2c(d) (d + '0')
void str_add(const char* s1, const char* s2, char* s_ret){
int s1_len = strlen(s1);
int s2_len = strlen(s2);
int max_len = s1_len;
int min_len = s2_len;
const char *ps_max = s1;
const char *ps_min = s2;
if(s2_len > s1_len){
ps_min = s1;min_len = s1_len;
ps_max = s2;max_len = s2_len;
}
int carry = 0;
int i, j = 0;
for (i = max_len - 1; i >= 0; --i) {
// this wrong-prone
int idx = (i - max_len + min_len) >=0 ? (i - max_len + min_len) : -1;
int sum = c2d(ps_max[i]) + (idx >=0 ? c2d(ps_min[idx]) : 0) + carry;
carry = sum / 10;
sum = sum % 10;
s_ret[j++] = d2c(sum);
}
if(carry)s_ret[j] = '1';
str_reverse(s_ret, s_ret + strlen(s_ret) - 1);
}
test code as below:
void test_str_str_add(){
char s1[] = "123";
char s2[] = "456";
char s3[10] = {'\0'};
str_add(s1, s2, s3);
std::cout<<s3<<std::endl;
char s4[] = "456789";
char s5[10] = {'\0'};
str_add(s1, s4, s5);
std::cout<<s5<<std::endl;
char s7[] = "99999";
char s8[] = "21";
char s9[10] = {'\0'};
str_add(s7, s8, s9);
std::cout<<s9<<std::endl;
}
output:
579
456912
100020
int num(char x,int len){
if(len <0)
return 0;
return ((x=='1') ? 1 : (x=='2') ? 2 : (x=='3') ? 3 : (x=='4') ? 4 : (x=='5') ? 5 : (x=='6') ? 6 : (x=='7') ? 7 : (x=='8') ? 8 : 9);
}
int main(){
int result[100];
int i=0;
char num1[] = "123456789123456789";
char num2[] = "1234567811111111111111111111";
int carry = 0;
int l1= strlen(num1)-1;
int l2 = strlen(num2)-1;
int result1;
while(1){
if(l1 < 0 && l2 <0 && carry == 0)
break;
result1 = num(num1[l1],l1) + num(num2[l2],l2);
l1--;
l2--;
if(carry>0){
result1 +=carry;
carry = 0;
}
carry = result1 / 10;
result[i] = (result1 % 10);
i++;
}
i--;
printf("\n");
while(i>=0){
printf("%d",result[i]);
i--;
}
}
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;
}