Convert int array to char array - c

I am having an array of integer say int example[5] = {1,2,3,4,5}. Now I want to convert them into character array using C, not C++. How can I do it?

Depending on what you really want, there are several possible answers to this question:
int example[5] = {1,2,3,4,5};
char output[5];
int i;
Straight copy giving ASCII control characters 1 - 5
for (i = 0 ; i < 5 ; ++i)
{
output[i] = example[i];
}
characters '1' - '5'
for (i = 0 ; i < 5 ; ++i)
{
output[i] = example[i] + '0';
}
strings representing 1 - 5.
char stringBuffer[20]; // Needs to be more than big enough to hold all the digits of an int
char* outputStrings[5];
for (i = 0 ; i < 5 ; ++i)
{
snprintf(stringBuffer, 20, "%d", example[i]);
// check for overrun omitted
outputStrings[i] = strdup(stringBuffer);
}

#include <stdio.h>
int main(void)
{
int i_array[5] = { 65, 66, 67, 68, 69 };
char* c_array[5];
int i = 0;
for (i; i < 5; i++)
{
//c[i] = itoa(array[i]); /* Windows */
/* Linux */
// allocate a big enough char to store an int (which is 4bytes, depending on your platform)
char c[sizeof(int)];
// copy int to char
snprintf(c, sizeof(int), "%d", i_array[i]); //copy those 4bytes
// allocate enough space on char* array to store this result
c_array[i] = malloc(sizeof(c));
strcpy(c_array[i], c); // copy to the array of results
printf("c[%d] = %s\n", i, c_array[i]); //print it
}
// loop again and release memory: free(c_array[i])
return 0;
}
Outputs:
c[0] = 65
c[1] = 66
c[2] = 67
c[3] = 68
c[4] = 69

You can convert a single digit-integer into the corresponding character using this expression:
int intDigit = 3;
char charDigit = '0' + intDigit; /* Sets charDigit to the character '3'. */
Note that this is only valid, of course, for single digits. Extrapolating the above to work against arrays should be straight-forward.

You need to create the array, because sizeof(int) is (almost surely) different from sizeof(char)==1.
Have a loop in which you do char_example[i] = example[i].
If what you want is to convert an integer into a string you could just sum your integer to '0' but only if you're sure that your integer is between 0 and 9, otherwise you'll need to use some more sophisticated like sprintf.

In pure C I would do it like this:
char** makeStrArr(const int* vals, const int nelems)
{
char** strarr = (char**)malloc(sizeof(char*) * nelems);
int i;
char buf[128];
for (i = 0; i < nelems; i++)
{
strarr[i] = (char*)malloc(sprintf(buf, "%d", vals[i]) + 1);
strcpy(strarr[i], buf);
}
return strarr;
}
void freeStrArr(char** strarr, int nelems)
{
int i = 0;
for (i = 0; i < nelems; i++) {
free(strarr[i]);
}
free(strarr);
}
void iarrtostrarrinc()
{
int i_array[] = { 65, 66, 67, 68, 69 };
char** strarr = makeStrArr(i_array, 5);
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", strarr[i]);
}
freeStrArr(strarr, 5);
}

Related

Why C dosen't split correctly arrays?

I have an array of 64 characters, which I need to divide into two parts, the left part of 32 characters and the right part, also 32 characters.
char *IP_M; // 64 characters array
char L[32]; // left part
char R[32]; // right part
The IP_M array is filled in as follow:
char *start_inital_permutation(const char *input) {
char *output = malloc(64 * sizeof(char));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
output[i * 8 + j] = input[IP[i][j] - 1];
}
}
return output;
}
...
IP_M = start_inital_permutation(M);
where M is also a 64 characters string. With the following method I tried to fill the other two array (L, R) by spliting the IP_M.
void fill_LR() {
for (int i = 0; i < 32; i++) {
L[i] = IP_M[i];
R[i] = IP_M[i + 32];
}
}
but when I run the following instructions:
printf("IP_M: %s\n", IP_M);
printf("L: %s\n", L);
printf("R: %s\n", R);
the output is:
IP_M: 1100110000000000110011001111111111110000101010101111000010101010
L: 1100110000000000110011001111111111110000101010101111000010101010
R: 11110000101010101111000010101010
I can't get out of this situation, can someone help me please?
*EDIT: also tried the memcpy() method but it still not work!
Here is the Project if someone want to see it:
https://github.com/ionutbogdandonici/DES_C.git
Strings in C are \0 terminated. So the print function will print the string until it reaches the \0 character.
Assign space for null:
char L[33]; // left part
char R[33]; // right part
Add null terminator:
void fill_LR() {
for (int i = 0; i < 32; i++) {
L[i] = IP_M[i];
R[i] = IP_M[i + 32];
}
L[32] = 0;
R[32] = 0;
}
output[i * 8 + j] = input[IP[i][j] - 1]; is gibberish.
Strings in C are null terminated but you never allocate space for a null terminator anywhere, nor do you null terminate your strings.
Don't use global variables.
I was able to salvage your program like this:
#include <stdio.h>
#include <stdlib.h>
char *start_inital_permutation(const char *input) {
size_t count=0;
char *output = malloc(64 * sizeof(char) + 1);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
output[i * 8 + j] = input[count++];
}
}
output[64] = '\0';
return output;
}
int main()
{
const char input[] = "1100110000000000110011001111111111110000101010101111000010101010";
char *IP_M = start_inital_permutation(input);
char L[32+1]; // left part
char R[32+1]; // right part
for (int i = 0; i < 32; i++) {
L[i] = IP_M[i];
R[i] = IP_M[i + 32];
}
L[32] = '\0';
R[32] = '\0';
printf("IP_M: %s\n", IP_M);
printf("L: %s\n", L);
printf("R: %s\n", R);
}
However, there's no apparent reason why you need to do the middle step with the 64 characters array. You could as well put that one in a union and save the copy (although then the individual left/right strings won't be null terminated). Example:
#include <stdio.h>
#include <stdlib.h>
typedef union
{
char data [64+1];
struct
{
char left[32];
char right[32];
char zero;
};
} ip_t;
ip_t *start_inital_permutation(const char *input) {
size_t count=0;
ip_t* obj = malloc(sizeof(ip_t));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
obj->data[i * 8 + j] = input[count++];
}
}
obj->data[64] = '\0';
return obj;
}
int main()
{
const char input[] = "1100110000000000110011001111111111110000101010101111000010101010";
ip_t *IP_M = start_inital_permutation(input);
printf("IP_M: %s\n", IP_M->data);
printf("L: %.32s\n", IP_M->left);
printf("R: %.32s\n", IP_M->right);
}
Using printf with "%s" assumes the value is a zero terminated string (AKA NULL terminated string).
I.e. a pointer to a sequence of chars, ending with a \0 char.
In your case when printf attempts to print L it prints char, and after the 32 chars that belong to L it continues. It happened to be that R is following L in memory, and so the content of R is also dumped. If the next byte in memory following R was not a 0, you would see even more characters printed. This behavior is dependent on the [possibly atrbitarary] content of your memory.
How to handle the issue (2 ways):
1. You can either increase the size of L and R to 33, and assign the last char to \0:
char L[33]; // left part
char R[33]; // right part
/* ... */
L[32] = '\0';
R[32] = '\0';
2. Or specify to printf the length of the strings (32) like this:
/*----------vvv-------*/
printf("L: %.32s\n", L);
printf("R: %.32s\n", R);
In the later case keep in mind that L and R are not "regular" C strings, which are expected to be zero terminated (at least as far as it concerns common functions like strlen, strcmp etc.).

How do I return a character array from char *functionName(int arrayname[SIZE]);

Assignment: Write a function that assumes the UPC code is an audio/video product, and returns a string indicating which product it is. this is the last function i have to write for this lab and I'm having trouble figuring out how to return a character array from this function. Barcode array is a 12 digit upc code entered by the user and the 10 space in the array indicated which type of media it is. After checking what the digit is, I want to return the indicated character array back to main to be printed.
char *getAudioVideoProductString(int barcodeArray[12]);
int main()
{
int barcodeArray[12];
do{
printf("\nEnter UPC code: ");
for(i = 0; i < 12; i++)
{
scanf("%d", &barcodeArray[i]);
}
avstring = getAudioVideoProductString(barcodeArray);
for(a = 0; a != '\0'; a++)
{
printf("%c", avstring[a]);
}
printf("\nAdd another UPC code [1 = add, 0 = quit]\n");
scanf("%d",&end);
}while(end !=0);
return EXIT_SUCCESS;
}
char *getAudioVideoProductString(int barcodeArray[12])
{
int i;
if (barcodeArray[10] == 1)
{
char b[] = "12\"\ LP or Single";
int lengthb = strlen(b);
char a[] = malloc(sizeof(char)*100);
for (i = 0; i < lengthb; i++)
{
a[i] = b[i];
}
}
if (barcodeArray[10] == 0| barcodeArray[10] == 3| barcodeArray[10] == 6)
{
char b[] = "Unassigned Audio Format";
int lengthb = strlen(b);
char a[] = malloc(sizeof(char)*100);
for (i = 0; i < lengthb; i++)
{
a[i] = b[i];
}
}
return a;
}
When I compile the program I get these errors:
char a[] = malloc(sizeof(char)*100); //-<< wrong a is not the pointer only the array
char *a = malloc(sizeof(char)*100); // -<< correct. you need the pointer to assign the address of the allocated memory
I think you need to read a bit about the arrays and pointers. Here on the SO are many topics about them. Just search.
PS
if you need the array:
char a[100];

Converting string to integer array in c

I am newbie to this topic.
I am trying to convert integer array to string. Then string to integer array to check if I am getting same input.
gint16 frame[5] = {10, 2, 3, 7, 5};
char *str = malloc(sizeof(char) * (sizeof(frame)+1));
char *strp = str;
size_t j;
for (j= 0; j < sizeof(frame); j++) {
snprintf(strp, 4, "%02x", frame[j]); //hexadecimal
strp++;
}
// from hexa string to 16 bit integer array
gint16 n_oframe[5];
size_t i_m;
for (i_m = 0; i_m < 5; i_m++) {
char *d = (char*)malloc(sizeof(gint16));
strncpy(d,str,2);
n_oframe[i_m] = atol(d);
str = str + 2;
free(d);
}
When I try to print out n_oframe values, I am getting in correct results. Please help me
Use these functions:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef int16_t gint16; // define gint16 if not compiling with glib.h
char *gint16_to_string(gint16 *p, int n) {
char *str = malloc(n * 4 + 1);
if (str) {
for (int i = 0; i < n; i++) {
snprintf(str + i * 4, 5, "%04X", p[i] & 0xFFFF);
}
}
return str;
}
void string_to_gint16(gint16 *p, int n, const char *str) {
if (str) {
for (int i = 0; i < n; i++) {
unsigned int x = 0;
sscanf(str + i * 4, "%4x", &x);
p[i] = (gint16)x;
}
}
}
int main(void) {
gint16 frame[5] = { 10, 2, 3, 7, 5 };
// encoding in hexadecimal
char *str = gint16_to_string(frame, 5);
printf("encoded string: %s\n", str);
// from hexa string to 16 bit integer array
gint16 n_oframe[5];
string_to_gint16(n_oframe, 5, str);
printf("n_oframe: ");
for (int i = 0; i < 5; i++) {
printf("%d, ", n_oframe[i]);
}
printf("\n");
free(str);
return 0;
}
The commenters found most of it, so to put it all together
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
// ALL CHECKS OMMITTED!
int main()
{
int16_t frame[5] = { 10, 2, 3, 7, 5 };
// hexadecimal string = 2 characters plus NUL
// sizeof(char) == 1, if compiler is standard compliant
char *str = malloc(3 * (sizeof(frame)/sizeof(frame[0]) +1));
char *strp = str;
size_t j;
for (j = 0; j < sizeof(frame)/sizeof(frame[0]); j++) {
// again: hexadecimal string = 2 characters plus NUL
snprintf(strp, 3, "%02x", frame[j]); //hexadecimal
strp += 2;
}
// we need a pointer to the start of the string to free it later
strp = str;
// let's see if we gott all of them
printf("str = %s\n",str);
// from hexa string to 16 bit integer array
int16_t n_oframe[5];
size_t i_m;
// and again: hexadecimal string = 2 characters plus NUL
// a simple char d[3]; would have been more than suffcient
// for the task, but if stack is precious...
char *d = (char *) malloc(3);
for (i_m = 0; i_m < 5; i_m++) {
// it's always the same, just do it once at the beginning
//char *d = (char *) malloc(3);
strncpy(d, str, 2);
// atol() is for base 10 input only, use strtol() instead
n_oframe[i_m] = (int16_t)strtol(d,NULL,16);
str = str + 2;
//free(d);
}
for (j = 0; j < 5; j++) {
printf("%d ", n_oframe[j]);
}
putchar('\n');
free(d);
free(strp);
exit(EXIT_SUCCESS);
}
I changed gint16 to int16_t because I do not know what that is supposed to be. You can most likely replace it with gint16 without problems.

Find product of 5 consecutive integer in C

I'm trying to calculate the product of 5 consecutive integer, but the result the completely wrong. I think my logic is correct, but why it shows me an unreal number: 344362200
The sequence number is from 1 to 10, code is below (just for testing only):
void problem8()
{
char *input = "123456789";
char c;
int step = 5, i = 0, prod = 0, temp = 1;
for (; i < step; i++)
{
temp *= *(input + i);
printf("%d\n", temp);
}
}
The output is really weird! At the first loop, the result is 42 ## while it should be 1, and 1 only. I checked individual result from *(input + 0) or 1 2 4 etc., it's correct. But the product is wrong.
You need to distinguish between the codes for the digits (48 for '0', 49 for '1', etc), and the numbers 1, 2, etc. You should be getting 49 on the first iteration; indeed, I get:
49
2450
124950
6497400
344362200
If you want the first 5 factorials, you'll need to use temp *= input[i] - '0'; (where input[i] is neater than *(input + i), IMNSHO).
The codes I gave are valid for code sets such as ISO 8859-1, and also UTF-8, and many other related code sets. They're not valid for EBCDIC, though.
The problem is that you are converting a char to an int, and not taking into account the ASCII offsets in the ASCII table. Integers start at hex 0x30 for ASCII.
#include <stdio.h>
#include <string.h>
int multiplyFiveSingleDigitNumbersInAString (const char* input, size_t inputLength);
int main(void) {
int tmp = 0;
const char* buf = "12345"; /* Create null-terminated string */
tmp = multiplyFiveSingleDigitNumbersInAString(buf, strlen(buf));
printf("Result of calculation for string %s is %d\n", buf, tmp);
return 0;
}
int multiplyFiveSingleDigitNumbersInAString (const char* input, size_t inputLength) {
if (inputLength != 5) {
printf("Wrong string length (%d), should be %d\n", (int)inputLength, 5);
return 0;
}
int i;
int multiSum = 1;
for (i=0; i<inputLength; i++) {
multiSum *= (int)input[i] - 0x30;
}
return multiSum;
}
References
ASCII Table, Accessed 2014-04-08, <http://www.asciitable.com/>
IMO, the other answers approach this backwards. Simply don't use chars when you want ints. Just change
char *input = "123456789";
to
int input = { 1, 2, 3, 4, 5 };
and your code will work.
P.S. Here's a solution to the actual problem:
char digits[] = "731...";
int main(void)
{
int max = 0;
for (int len = sizeof digits - 1, i = 0; i < len - 4; i++)
{
int prod = 1;
for (int j = 0; j < 5; j++)
prod *= digits[i + j] - '0';
if (max < prod) max = prod;
}
printf("%d\n", max);
return 0;
}

How to write a getline function in C?

I know that getline is C++ standard but I need to read a line of digits:
123856
and save it to an array. But how to do this without spaces between given (as input) digits? I want a user input to be:
123856 (with no spaces) and then save it to an array (n element array) and after that, I want my array to look like this:
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 8;
array[4] = 5;
array[5] = 6;
But how to make it in C, without a getline?
This is NOT what I want:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char **argv)
{
int t[4];
int i;
for(i=0; i<4; i++)
scanf("%d", &t[i]);
for(i=0; i<4; i++)
printf("%d\n", t[i]);
return 0;
}
If I understood you correct, the following should do it:
read the whole line
loop through the string as long as you get digits or the string ends
for every digit, place it's value in your array and increase the index by 1
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
/* If desired, add check for value outside of 0-9 */
array[ i++ ] = c - '0';
...
}
char arr[] = "1234567";
int intarr[10];
int count = 0;
for (char* ptr = arr; *ptr; ptr++) {
intarr[count] = *ptr - '0';
count++;
}
try this
#include <stdio.h>
#include <string.h>
main (int argc, char *argv[])
{
FILE *f;
int i=0;
int j=0;
char output[100];
char* output1[100];
char string[100];
char delims1[] = " ";
char delims2[] = "*";
char* result = NULL;
char* result3 = NULL;
int num;
//for (j=0; j<2; j++)
//{
//printf("%s",delims9[6]);
//}
f = fopen("text.txt","r");
//
while( fgets(string,sizeof(string),f) )
{
result = strtok( string, delims1 );
while( result != NULL )
{
output1[i]=result;
printf("%s\n",output1[i]);
result = strtok( NULL, delims1 );
i++;
}
for (num = 0; num < 100; i++ ) //
{ // Error On this array
printf("%s\n", output1[i]); //
} //
}
printf("\n%d",i/3+1);
return 0 ;
}
Ok, without using any string.
int digits = 123856;
int numofdigits = 1 + floor(log10(digits));
int digits_arr[numofdigits];
int i;
for(i = numofdigits-1; i >= 0; i--) {
digits_arr[i] = (int)floor(digits / pow(10, i)) % 10;
}
Try the below link... Same question asked here and get solution....
convert an integer number into an array
char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}

Resources