I have written the code that converts decimal to binary number, but I am having trouble with having a set of inputs, which are 4 test cases and having them to pass.
Can someone help me out with what I am doing wrong?
#include <stdio.h>
int main(void) {
int quotient, i, j, bin[16] = {0};
int decimal1, decimal2, decimal3, decimal4;
decimal1 = 123;
decimal2 = 1024;
decimal3 = 43981;
decimal3 = 2005;
scanf("%d", "ient);
i = 0;
if (quotient == 0) {
bin[i++] = 0;
}
while (quotient != 0) {
bin[i] = quotient % 2;
quotient = quotient / 2;
i = i + 1;
}
printf(" The Binary value is: ");
for (j = 15; j >= 0; j--)
printf("%d", bin[j]);
return 0;
}
#include <stdio.h>
#include <limits.h>
char *tobin(long value, char *buff, int type)
{
union
{
long l;
unsigned long lu;
}lunion;
char *savedptr = buff;
char *reverse = buff;
char savedchar;
if(type)
{
if(value == LONG_MIN)
{
lunion.lu = 1UL << (sizeof(value) * 8) - 1;
}
else
{
lunion.lu = (value < 0) ? -value : value;
}
}
else
{
lunion.l = value;
}
do
{
*buff++ = (lunion.lu & 1) ? '1' : '0';
lunion.lu >>= 1;
}while(lunion.lu);
if(type && value < 0)
{
*buff++ = '-';
}
*buff-- = 0;
while(buff > reverse)
{
savedchar = *buff;
*buff-- = *reverse;
*reverse++ = savedchar;
}
return savedptr;
}
int main()
{
char x[100];
printf("%ld = %s\n", LONG_MIN, tobin(LONG_MIN, x, 1));
printf("%ld = %s\n", LONG_MIN, tobin(-1, x, 1));
printf("%ld = %s\n", LONG_MIN, tobin(-400, x, 1));
printf("%ld = %s\n", 0L, tobin(0, x, 1));
printf("%ld = %s\n\n\n", LONG_MAX, tobin(LONG_MAX, x, 1));
printf("%ld = %s\n", LONG_MIN, tobin(LONG_MIN, x, 0));
printf("%ld = %s\n", LONG_MIN, tobin(-1, x, 0));
printf("%ld = %s\n", LONG_MIN, tobin(-400, x, 0));
printf("%ld = %s\n", 0L, tobin(0, x, 0));
printf("%ld = %s\n", LONG_MAX, tobin(LONG_MAX, x, 0));
}
Related
So I have a code that gets two integers, converts them to int[32] strings, and does more by a simulated full adder circuit(this is to implement it to an Arduino circuit).
This is the whole code:
#include<stdio.h>
int relay(int ctrl, int input, int mode) {
printf(" Relay used ");
if (mode == 0) {
if (ctrl == 1 && (input == -1 || 1)) {
return input;
}
else
return 0;
}
else if (mode == 1) {
if ((ctrl == 0 || -1) && (input == -1 || 1)) {
return input;
}
else
return 0;
}
printf("ERR ON FUNCTION relay");
return 10000;
}//Relay circuit simulation(mode 0=naturally open,mode 1=naturally closed)
int andgate(int in1, int in2) {
printf(" AND gate used (");
int relayout = relay(in1, in2, 0);
printf(")");
if (relayout <= 0)
return 0;
else if (relayout == 1)
return 1;
printf("ERR ON FUNCTION andgate");
return 10000;
}//AND Gate circuit simulation
int orgate(int in1, int in2) {
printf(" OR Gate used ");
if (in1 || in2 == 1)
return 1;
else
return 0;
printf("ERR ON FUNCTION orgate");
return 10000;
}//OR Gate circuit simulation
int nandgate(int in1, int in2) {
printf(" NAND gate used (");
if (relay(in1, relay(in2, -1, 0), 0) == -1) {
printf(")");
return 0;
}
else if (relay(in1, relay(in2, -1, 0), 0) == 0) {
printf(")");
return 1;
}
printf("ERR ON FUNCTION nandgate");
return 10000;
}//NAND Gate circuit simulation
int xorgate(int in1, int in2) {
printf(" XOR gate used (");
int orout, nandout;
orout = orgate(in1, in2);
nandout = nandgate(in1, in2);
printf(")");
return andgate(orout, nandout);
printf("ERR ON FUNCTION xorgate");
return 10000;
}//XOR Gate circuit simulation
int hout, hc;
void hadder(int in1, int in2) {
printf(" Half adder used (");
//hout,hc : hadder output
hout = xorgate(in1, in2);
hc = andgate(in1, in2);
printf(")");
}//Half adder circuit simulation
int fout, fc;
void fadder(int in1, int in2, int c) {
printf(" Full adder used (");
int hout1, hc1;//hout,hc : hadder output, fout,fc : fadder output
hadder(in1, in2);
hout1 = hout; hc1 = hc;
hout = 0; hc = 0;
hadder(hout1, c);
fout = hout;
fc = orgate(hc1, hc);
printf(")");
}//Full adder circuit simulation
int lcheck(int leanth, int check[]) {
int bincheck[2] = { 0, };
for (int i = 0; i < leanth; i++) {
if (check[i] == 0 && bincheck[0] == 0) {
bincheck[0] = 1;
bincheck[1] = i;
}
else if (check[i] == 1) {
bincheck[0] = 0;
}
}
return bincheck[1];
}
int BintoDec(int binary[], int leangth/*unused*/)
{
int decimal = 0;
int position = 0;
for (int i = 31; i >= 0; i--)
{
if (binary[i] == 1)
printf("\n%d %d", binary[i], position);
decimal += 1 << position;
position++;
}
return decimal;
}
int main() {
int input = 0, input2 = 0;
int mask;
int ahcw[32] = { 0, }, ahcw2[32] = { 0, }, pahcw[32] = { 0, }, dahcw[32] = { 0, };
int lahcw, lahcw2, ldahcw, ssum;
printf("Input Number:");
scanf_s("%d", &input);
printf("Input Number:");
scanf_s("%d", &input2);
for (int i = 31; i >= 0; i--) {
mask = 1 << i;
ahcw[i] = input & mask ? 1 : 0;
}
lahcw = lcheck(32, ahcw);
printf("\n\n%d\n\n", lahcw);
for (int i = 31; i >= 0; i--) {
mask = 1 << i;
ahcw2[i] = input2 & mask ? 1 : 0;
}
lahcw2 = lcheck(32, ahcw);
if (lahcw >= lahcw2)
ssum = lahcw;
else
ssum = lahcw2;
for (int i = 0; i < ssum + 1; i++) {
fadder(ahcw[i], ahcw2[i], pahcw[i]);
dahcw[i] = fout;
pahcw[i + 1] = fc;
}
ldahcw = lcheck(32, dahcw);
printf("%d ", ldahcw);
for (int i = 31; i >= 0; i--) { printf("%d", dahcw[i]); if (i % 8 == 0) printf(" "); }
printf("\n\n\n\n\n\n%d", BintoDec(dahcw, 33));
}
but the problem I am facing with is in the BintoDec function.
int BintoDec(int binary[], int leangth/*unused*/)
{
int decimal = 0;
int position = 0;
for (int i = 31; i >= 0; i--)
{
if (binary[i] == 1)
printf("\n%d %d", binary[i], position);
decimal += 1 << position;
position++;
}
return decimal;
}
which should output a converted binary integer which it does when I put in an int[32] string formatted to {0,0,...,1,0,0}(outputs 4), but if I put the output of the first code(dahcw), it just spits out what seems to be a random integer.
Sorry for my bad English, it's my second language.
Edit:I have put the printf statement in my BintoDec function for debugging purposes, but it pushed decimal += 1 << position; out of the if statement, braking the function.
The quick fix would be to remove the printf statement, but I do prefer #Fiddling Bits's answer for the use of unsigned ints instead of normal ints.
And this part on the relay function ctrl == 0 || -1 had to be changed to ctrl == -1 || 0, but for some reason, it still worked without the fix.
If BintoDec is your only problem, which it probably isn't as pointed out by #Govind Parmar, this should fix your problem:
#include <stdio.h>
unsigned int BintoDec(int binary[], int length)
{
unsigned int decimal = 0;
for (int i = 0; i < length; i++)
{
if(binary[i] == 1)
decimal |= (1 << (length - i - 1));
}
return decimal;
}
int main(void)
{
int binary[32] = {1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1};
unsigned int decimal;
for(int i = 0; i < 32; i++)
{
printf("%d", binary[i]);
if((i != 0) && (((i + 1) % 4) == 0) && (i != 31))
printf(", ");
}
printf("\n");
decimal = BintoDec(binary, 32);
printf("0x%08X\n", decimal);
return 0;
}
Output:
$ gcc main.c -o main.exe; ./main.exe
1101, 1110, 1010, 1101, 1011, 1110, 1110, 1111
0xDEADBEEF
I think I've figured it out!
The BintoDec function accepts strings in this manner. For instance, the number 4 is
int a[32]={0,0,...,0,0,1,0,0}, which means a[29] is 1 and every other number is 0.
But I was converting the integer to a binary string using this piece of code.
for (int i = 31; i >= 0; i--) {
mask = 1 << i;
ahcw[i] = input & mask ? 1 : 0;
}
which if it were to convert 4, it would end up with a string like this{0,0,1,0,0,...,0,0},meaning that ahcw[2] is 1 and every other number is 0.
So, I basically needed code to flip the string so that the BintoDec function could interpret the string properly.
int fdahcw[32];
for (int i = 0; i < 32; i++) {
fdahcw[31 - i] = dahcw[i];
}
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
My file input contains the chars "abc" and is supposed to generate the hash: "a9993e364706816aba3e25717850c26c9cd0d89d" Instead, my output is 2474716729 148412417 414899454 2419217526 3285377520. My bit shifting should be correct but when I print out my W[t] I'm pretty sure the numbers are wrong.
#include <stdio.h>
#define MAX_SIZE 1048576
static unsigned char buffer[MAX_SIZE];
static unsigned int message[MAX_SIZE];
unsigned int readFile(unsigned char buffer[])
{
size_t length = 0;
int b = 0;
for (b = 0; b < MAX_SIZE; b++)
{
buffer[b]= '\0';
}
int i = 0;
char *fileName = "abc.txt";
FILE *filePointer = fopen(fileName, "r");
if (filePointer != NULL)
{
length = fread(buffer, sizeof(char), MAX_SIZE, filePointer);
if (ferror(filePointer)!= 0)
{
fputs("Error", stderr);
}
if (length > MAX_SIZE)
{
fputs("Input file too big for program", stderr);
}
//add one bit;
buffer[length] = 0x80;
//length++;
}
/*for (i = 0; i < MAX_SIZE; i++)
{
printf("%c", buffer[i]);
}
*/
fclose(filePointer);
return length;
}
unsigned int calculateBlocks(unsigned int sizeOfFileInBytes)
{
int blockCount = (((8 * sizeOfFileInBytes) + 1) / 512) + 1;
if((((8 * sizeOfFileInBytes) + 1) % 512) > (512 - 64))
{
blockCount = blockCount + 1;
}
//printf("here's block count: %i", blockCount);
return blockCount;
}
void convertCharArrayToIntArray(unsigned char buffer[], unsigned int
message[], unsigned int sizeOfFileInBytes)
{
int e = 0;
int d = 0;
//buffLength shows me how many chars are in array
size_t buffLength= strlen((char*)buffer);
//printf("this is bufflength: %zu -done", buffLength);
buffLength = buffLength/4;
for (e=0 ; e< buffLength; e++)
{
message[e] |= (buffer[e] <<24);
message[e] |= (buffer[e+1] <<16);
message[e] |= (buffer[e+2] <<8);
message[e] |= (buffer[e+3]);
}
/*for (d = 0; d <MAX_SIZE; d++)
{
printf("%i", message[d]);
} */
//printf("- done with message[d]");
}
void addBitCountToLastBlock(unsigned int message[], unsigned int
sizeOfFileInBytes, unsigned int blockCount)
{
int indexOfEndOfLastBlock = blockCount* 16 -1;
//printf("the size of file in bytes is: %i -done",
sizeOfFileInBytes);
sizeOfFileInBytes = sizeOfFileInBytes * 8;
message[indexOfEndOfLastBlock] = sizeOfFileInBytes;
//printf("index of last block is %i", message[indexOfEndOfLastBlock]);
int d = 0;
/* for (d = 0; d <MAX_SIZE; d++)
{
printf("%i", message[d]);
}
printf("- done with message[d]"); */
}
unsigned int K(unsigned int t)
{
unsigned int kHex[] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6};
if (t>= 0 && t <= 19)
{
return kHex[0];
}
else if (t>= 20 && t <= 39)
{
return kHex[1];
}
else if (t>= 40 && t <= 59)
{
return kHex[2];
}
else if (t>= 60 && t <= 79)
{
return kHex[3];
}
return 0;
}
unsigned int f(unsigned int t, unsigned int B, unsigned int C, unsigned
int D)
{
if (t>= 0 && t <= 19)
{
return (B & C) |((~B)&D);
}
else if (t>= 20 && t <= 39)
{
return B^C^D;
}
else if (t>= 40 && t <= 59)
{
return (B & C) | (B & D) | (C & D);
}
else if (t>= 60 && t <= 79)
{
return B^C^D;
}
return 0 ;
}
void computeMessageDigest(unsigned int message[], unsigned int
blockCount)
void computeMessageDigest(unsigned int message[], unsigned int
blockCount)
{
unsigned int A, B, C, D, E;
unsigned int h[5];
unsigned int W[80];
unsigned int t = 0;
unsigned int temp; //temporary word value
unsigned int bCounter = 0;
int i = 0;
int d = 0 ;
// int z = 0;
//int blCount = 0;
/* for (d = 0; d <MAX_SIZE; d++)
{
printf("%i", message[d]);
}
printf("- done with message[d]"); */
int wInc = 0;
h[0] = 0x67452301;
h[1] = 0xefcdab89;
h[2] = 0x98badcfe;
h[3] = 0x10325476;
h[4] = 0xc3d2e1f0;
while ( bCounter < blockCount)
{
for (i= 16 * bCounter; i < 16 *bCounter +16; i++)
{
W[wInc] = message[i];
wInc++; //block one
}
wInc = 0;
/*for (z = 0; z < 16; z++)
{
printf("%i", W[z]);
} */
for (t = 16; t < 80; t++)
{
W[t] = (W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]) << 1;
// printf("%u ", W[t]);
}
A = h[0];
B = h[1];
C = h[2];
D = h[3];
E = h[4];
for (t = 0; t < 80; t++)
{
temp = (A << 5) + f(t, B, C, D) + E + W[t] + K(t);
E = D;
D = C;
C = B << 30;
B = A;
A = temp;
}
printf("Hex values for A, B, C, D, E");
printf("%u, %u, %u, %u, %u", A, B, C, D, E) ;
h[0] += A;
h[1] += B;
h[2] += C;
h[3] += D;
h[4] += E;
int b = 0;
for (b = 0; b <5; b++)
printf("%u ", h[b]);
bCounter++;
}
int main(int argc, const char * argv[]) {
// insert code here...
unsigned int blockCount = 0;
unsigned int sizeOfFile = 0;
sizeOfFile = readFile(buffer);
/*for (i = 0; i < MAX_SIZE; i++)
{
printf("%c", buffer[i]);
} */
//printf("%i is the size", readFile(buffer));
blockCount = calculateBlocks(sizeOfFile);
convertCharArrayToIntArray(buffer, message, sizeOfFile);
//printf("\n");
addBitCountToLastBlock(message, sizeOfFile, blockCount);
computeMessageDigest(message, blockCount);
return 0;
So I understand how to perform calculations on integers represented in strings and then printing the result in a string. But I'm lost on how to do the same thing with a decimal in the number represented in a string.
Here's how I did it with integers. This part of the code is adding together two integers:
int answer = 0;
char str1[100];
int count = 0;
int total = 0;
int k = 0;
int diff = 0;
if (ele == ele2) {
for (k = strlen(op1) - 1; k > -1; k--) {
if ((strspn(operand, "+") == strlen(operand))) {
answer = (op1[k] - '0') + (op2[k] - '0');
} else if ((strspn(operand, "-") == strlen(operand))) {
answer = (op1[k] - '0') - (op2[k] - '0');
}
total += (pow(10, count) * answer);
count++;
}
sprintf(str1, "%d", total);
printf("Answer: %s ", str1);
}
Output
// 12 + 14
Answer: 26 // Answer given as a string
Example
12.2 + 14.5 // Three strings
Answer: 16.7 // Answer as string
Current Attempt:
for (k = strlen(argv[1]) - 1; k > -1; k--) {
if (argv[1][k] == '.') {
dec = k;
} else {
answer = (argv[1][k] - '0') + (argv[3][k] - '0');
total += (pow(10, count) * answer);
count++;
}
}
// needs to be converted to a long?
// ele is the length of the operand
total = total / pow(10, ele - dec);
sprintf(str1, "%d", total);
printf("Answer: %s ", str1);
Sharing a simple algo to begin with (and assuming your adding integer funciton works fine).
A decimal number is basically two integers separated by ".".
Identify the position of "." and grab the two sides of the integer as integerPart, decimalPart
One caveat on getting the decimalPart is that the length of all the decimalParts should be same, if not, add "0"s in the suffix.
Add the integerPart, add the decimalPart and handle the carryForwards in the decimalPart.
So,
12.2 + 14.95
= (12 + 14) (20 + 95)
= 26 115
= 26+1 15
= 27.15
This is a quick and dirty implementation: no parameter check, no deep test only an idea of how you should process.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int total_digits;;
int decimal_points;
int *number;
} NUMBER, *DECIMALNUMBER;
DECIMALNUMBER initilize(char *str)
{
DECIMALNUMBER result = calloc(1, sizeof(NUMBER));
int in_decimal = 0;
char *s;
int i;
for (s = str; *s; s++)
{
if (isdigit(*s))
{
result->total_digits++;
if (in_decimal)
{
result -> decimal_points++;
}
}
else if (*s == '.')
{
in_decimal = 1;
}
else
{
return NULL;
}
}
result->number = calloc(result->decimal_points, sizeof(int));
i=0;
for (s = str; *s; s++)
{
if (isdigit(*s))
{
result->number[i++] = (int)(*s - '0');
}
}
// printf("result->total_digits is %d\n",result->total_digits);
// printf("result->decimal_points is %d\n",result->decimal_points);
// printf("result is %d\n",result->number[--i]);
// printf("result is %d\n",result->number[--i]);
// printf("result is %d\n",result->number[--i]);
return result;
}
void print_number(DECIMALNUMBER p)
{
int i;
for (i=0; i<p->total_digits; i++)
{
if (i==p->total_digits - p->decimal_points) {
printf(".");
}
printf("%d", p->number[i]);
}
printf("\n");
}
DECIMALNUMBER sum(DECIMALNUMBER a, DECIMALNUMBER b)
{
int max_decimals = a->decimal_points>b->decimal_points ? a->decimal_points : b->decimal_points;
int max_digits_count = a->total_digits>b->total_digits ? a->total_digits : b->total_digits;
DECIMALNUMBER result = calloc(1, sizeof(NUMBER));
result->total_digits = max_digits_count;
result->decimal_points = max_decimals;
result->number = calloc(max_digits_count, sizeof(int));
int i1 = a->total_digits-1;
int i2 = b->total_digits-1;
int i3 = result->total_digits-1;
int remainder = 0;
int summed;
while (i1 >= 0 || i2 >=0)
{
int aa = i1 < 0 ? 0 : a->number[i1];
int bb = i2 < 0 ? 0 : b->number[i2];
summed = aa + bb + remainder;
result->number[i3] = summed % 10;
remainder = summed / 10;
i1--;
i2--;
i3--;
}
return result;
}
int main()
{
DECIMALNUMBER a = initilize("12.2");
DECIMALNUMBER b = initilize("16.7");
print_number(a);
print_number(b);
DECIMALNUMBER c = sum (a,b);
print_number(c);
return 0;
}
How can I convert a long variable to a char[] variable without using library functions?
Working example (1) - thread-safe, requires min. buffsize = 40.
static const char *
xllitoa(long long int x, char *buff)
{
char *p = buff + 40;
int sign = 0;
*(p--) = 0;
if (x < 0) sign = 1;
else x = -x;
do { *(p--) = -(x % 10) + '0'; x /= 10; } while(x);
if (sign) *(p--) = '-';
return (const char *)(p+1);
}
Working example (2) - not thread-safe
static const char *
xllitoa(long long int x)
{
static char buff[40];
char *p = buff + 40;
int sign = 0;
*(p--) = 0;
if (x < 0) sign = 1;
else x = -x;
do { *(p--) = -(x % 10) + '0'; x /= 10; } while(x);
if (sign) *(p--) = '-';
return (const char *)(p+1);
}
Many thanks to reviewers. Now it accepts LLONG_MAX and LLONG_MIN as well.
After accept answer that works for all values LONG_MIN to LONG_MAX.
This uses a helper function to recursive work with negative values of n. By using negative values, there is no problem with LONG_MIN.
static char *ltostr_helper(long n, char *dest) {
if (n <= -10)
dest = ltostr_helper(n / 10, dest);
*dest++ = (char) ('0' - n % 10);
return dest; // return pointer to end
}
void ltostr(long n, char *dest) {
if (n < 0) {
*dest++ = '-';
} else {
n = -n;
}
*ltostr_helper(n, dest) = '\0';
}
int main(void) {
char buf[sizeof(long) * CHAR_BIT /3 + 3];// size buffer to our needs
ltostr(0, buf); printf("%s\n", buf);
ltostr(123, buf); printf("%s\n", buf);
ltostr(-123, buf); printf("%s\n", buf);
ltostr(LONG_MAX, buf); printf("%s\n", buf);
ltostr(LONG_MIN, buf); printf("%s\n", buf);
return 0;
}
Output
0
123
-123
9223372036854775807
-9223372036854775808