Convert Char Array to Single Int

Convert char array to a int number in C

I personally don't like atoi function. I would suggest sscanf:

char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);

It's very standard, it's in the stdio.h library :)

And in my opinion, it allows you much more freedom than atoi, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.

EDIT
I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi, sscanf and strtol. Also, there is a nice more-detailed insight into sscanf (actually, the whole family of *scanf functions).

EDIT2
Looks like it's not just me personally disliking the atoi function. Here's a link to an answer explaining that the atoi function is deprecated and should not be used in newer code.

How to convert array of char into array of int in C Programming?

You are confusing single characters with character strings. The latter are sequences of characters (arrays) terminated with a nul (zero value) character, and that is what the atoi function expects as its input.

To convert a single character digit to its numerical value, you just need to subtract the value of the zero digit ('0') from that character's value (the values of the numerical digits are guaranteed by the Standard to be contiguous).

So, rather than:

array[i] = atoi(&parray[i]);

use:

array[i] = parray[i] - '0'; // Will work if (and only if) parray[i] is a digit.

What is happening in your code is that (by chance) there is a zero byte immediately after the end of your 5-character array (but you can not rely on this), so each atoi(&parray[i]) call is passing a character string starting with, respectively, the '7', '1', '5', '4' and '2' characters, and ending only after the '2'. Thus, you are getting values that represent the numbers formed by the concatenation of your individual array digits. But I repeat: you cannot rely on there being a zero-value character after your array!

how to cast an array of char into a single integer number?

You cast (char*) to (int). What you should do is cast to pointer to integer, i.e.

t_num = *((int*) s_num));

But really you should extract your code into it's own function and make sure that:

  1. endianness is correct
  2. sizeof(int) == 4
  3. Use C++ casts (i.e. static, dynamic, const, reinterpret)

How to convert a char array of hex values to a single integer value in c++?

#include <stdint.h>
#include <iostream>

int main(int argc, char *argv[]) {
unsigned char cArray[4] = { 0x00, 0x09, 0x27, 0xC0 };
uint32_t nHexNumber = (cArray[0] << 24) | (cArray[1] << 16) | (cArray[2] << 8) | (cArray[3]);

std::cout << std::hex << nHexNumber << std::endl;
return 0;
}

Edited: As pointed out by M.M this is not depending on endianness as originally stated.

Output under QEMU:

user@debian-powerpc:~$ uname -a
Linux debian-powerpc 3.2.0-4-powerpc #1 Debian 3.2.51-1 ppc GNU/Linux
user@debian-powerpc:~$ ./a.out
927c0
user@debian-powerpc:~$

Under Ubuntu on Windows:

leus@owl:~$ uname -a
Linux owl 4.4.0-43-Microsoft #1-Microsoft Wed Dec 31 14:42:53 PST 2014 x86_64 x86_64 x86_64 GNU/Linux
leus@owl:~$ ./a.out
927c0
leus@owl:~$

Convert char array to integer value

I really hope that this helps you. From what I understood so far this will grab the bytes that are within the start to end range and will place them in an integer:

// here I am converting the chars from hex to int
int getBitPattern(char ch)
{
if (ch >= 48 && ch <= 57)
{
return ch - '0';
}
else if (ch >= 65 && ch <= 70)
{
return ch - 55;
}
else
{
// this is in case of invalid input
return -1;
}
}

int getValue(const char* memory, int start, int end)
{
if (end <= start)
return 0;

unsigned int retVal = 0;

//now just add up array fields
for (int i = end, j = 0; i >= start; i--, ++j)
{
fprintf(stdout, "\n%02hhx", memory[i]);
// bitshift in order to insert the next set of 4 bits into their correct spot
retVal |= (getBitPattern(memory[i]) << (4*j));
}
fprintf(stdout, "\n\n\n%d", retVal);
return retVal;
}

How to convert char array into int?

I've solved my problem. I used list to accomplish the task.

I stored each array index at the relative index of the list after converting each index value to int.

Using list seems more convenient way to me. :)

Thanks to all of you.

How to convert an char array (like {1-345}) into an Int array

I am using the simple approach of type casting from character to integer as,
N[i] = (int)s[i] -'0';

Here N is integer array , s is the character array .I simply type cast the character array into integer , it will treat it as a ASCII code of s[i]. so I minus the '0' character (this show the number must be in original value not in ascii code).

You can try the below code!
Also I am attaching the screenshot of the output of code.

#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
//character array 's' with length of 5
char s[5] = { '1', '3', '2', '5', '6' };

//before converting , prints the character array
cout << "\t\tCharacter Array" <<endl;
for (int i = 0; i < 5; i++)
{
cout << s[i] << "\t";
}

//integer array 'N' with length of 5
int N[5];
cout << "\n\tConverting Character Array to Integer Array" << endl;
//convert the character array into integer type and assigning the value into integer array 'N'
for (int i = 0; i < 5; i++)
{
N[i] = (int)s[i] - '0';
}

cout << "\t\tInteger Array" << endl;
//after converting , prints the integer array
for (int i = 0; i < 5; i++)
{
cout <<N[i]<<"\t";
}

_getch();
return 0;
}

Output of the code

Convert char array into an array of integers in C

given the posted code, which does not compile:

    int i=0;
size_t dim = 1;
char* array = (char*)malloc(dim);

while (proc.available()){

array[i] = (char)proc.read();
dim++;
i++;
array = (char*)realloc(array,dim);

}

it can be turned into a compilable function by:

void allocateArray()
{
int i=0;
size_t dim = 1;
char* array = (char*)malloc(dim);

while (proc.available())
{

array[i] = (char)proc.read();
dim++;
i++;
array = (char*)realloc(array,dim);
}
}

then re-arranged to eliminate unnecessary calls to system functions and adding error checking:

char * allocateArray()
{
int i=0;
size_t dim = 1;
char* array = NULL;

while (proc.available())
{
char *temp = realloc(array,dim);
if( NULL == temp )
{
perror( "realloc failed" );
free( array );
exit( EXIT_FAILURE );
}

// implied else, malloc successful

array[i] = (char)proc.read();
dim++;
i++;
}
return array;
} // end function: allocateArray

The above has some problems:

  1. it only allocates a single char, regardless of actual number of characters in each array entry.
  2. It does not produce an array of integers.
  3. there is no way to acquire multiple characters

We could address some of these problems by:

  1. modifying the function: proc.read() to return a pointer to a NUL
    terminated char string rather than just a single character
  2. converting that char string to an integer
  3. allocating enough new memory at each iteration to hold an integer

which would result in:

int * allocateArray()
{
int i=0;
size_t dim = 1;
int* array = NULL;

while (proc.available())
{
int *temp = realloc(array,dim*sizeof(int));
if( NULL == temp )
{
perror( "realloc failed" );
free( array );
exit( EXIT_FAILURE );
}

// implied else, malloc successful

array = temp;
array[i] = atoi(proc.read());
dim++;
i++;
}
return array;
} // end function: allocateArray

however, there are still some problems. Specifically a C program cannot have functions named: proc.available() nor proc.read()



Related Topics



Leave a reply



Submit