Running the code below prints b = and i = 15.
int i = 15;
char b = (char) i;
printf("b = %c and i = %d\n", b, i);
How can I store this integer in the character? At the end I'm trying to have a char array of size 1024 which has i (15) as the first character and rest 0.
update: I tried :
int i = 15;
char buffer[1024];
snprintf(buffer, 10, "%d", i);
printf("buffer[0] = %c, buffer[1] = %c\n", buffer[0], buffer[1]);
And the result printed was:
buffer[0] = 1 , buffer[1] = 5
You did store the integer in the character, it's just that %c converts a character to its ASCII value. All ASCII values below 31 are non-printable.
If you run
printf("b = %d and i = %d\n", (int)b, i);
it will print 15.
If you want a representation of i as a string:
char buf[12]; //Maximum number of digits in i, plus one for the terminating null
snprintf(buf, 12, "%d", i);
This will store a string representation of i in buf.
A char is an 8-bit unsigned value (0 - 255) and it does indeed store 15 in it, the problem is, that in ASCII table 15 means "shift in" non-printable character, and %c interprets the value as an ascii character.
char b = (char) i;
printf("b = %d and i = %d\n", b, i);
to get
b = 15 and i = 15
if you used i = 90 in your current code, this would be printed:
b = Z and i = 90
The problem here is, variable b already has a value 15 but since this does not constitute to a printable ASCII, using %c format specifier, you won't be able to see any output.
To print the value, use %hhd format specifier.
At the end I'm trying to have a char array of size 1024 which has i (15) as the first character and rest 0.
Well, you can define an array and assign values accordingly. Something like
#define SIZE 1024
char arr [SIZE] = {0}; //initialization, fill all with 0
arr[0] = 15; //first value is 15
should do the job.
Clarification:
The range of char is -128..127.
The range of unsigned char is 0..255.
If capturing ASCII values is the goal, declaring buffer variable to unsigned char type seems to be more appropriate.
You can't store Integer datatype in Character datatype(datatype conflict).
But what you are want, can be achieved by taking 2-dimensional character array.
char b[1024][1024];
itoa(i,b[0],20); ///
for(int i = 1 ; i < 1024 ; i++)
itoa(0,b[i],20);
Function itoa converts integer into character array and stores it into the character array. Hope it helps.
click here for more info :)
Related
I want to convert string "hello world" to some integer value and get back "hello world" string from converted integer value. I tried but getting issue while converting int to string.
I converted the string to an integer using this code:
char str[50];
int i, len; int result=0;
printf("Enter string to be converted: ");
gets(str);
len = strlen(str);
for(i=0; i<len; i++){
result = result * 10 + ( str[i] - '0' );
}
printf("%d\n", result);
and then I tried converting it back like this:
printf("%d\n", result);
int rem; int j = 0;
char result_str[50];
while (result !=0) {
result = result - '0' ;
rem = result%10 ;
result = result/10;
result_str[j] = 'a' + (rem -1);
printf("%c",result_str[j]); j++;
}
printf("result string = %s",result_str);
Sample output:
$ ./a.out
Enter string to be converted: hello
619663
619663
eccfhresult string = eccfh
When I try the string "hello world" I get a segmentation fault.
There is absolutely no way to convert a string to an int and then back again the way you want.
An int is typically 4 bytes, and you're using a char[50] which is 50 bytes. This means that an int can have 2³² different values, while a char[50] can have 2⁴⁰⁰ different values. So it is simply impossible to map them one to one.
Let's take an example outside the realm of code and computers and just focus on numbers. Can you imagine a method to convert a two-digit number to a one-digit number and back? If this was possible, then we would not need two digits in the first place. If such a method existed, you would be able to store an infinite amount of data in a single bit.
You can convert a char[4] to an int and back. It's actually really easy. This code will print abcd.
char str[4] = { 'a', 'b', 'c', 'd'};
// Convert to int
int result = *(int*) str;
char newstr[4];
// Convert back
char * ptr = (char*) &result;
for(int i=0; i<4; i++)
newstr[i] = ptr[i];
printf("%.4s\n", newstr);
Note that I completely ignored termination of the string, and just instructed printf to stop after four characters.
Oh, and never use the gets function. It's dangerous.
I am converting string arguments into ints I am having an issue where the first argument is not copying and converting to a string while the second argument is working just fine. I am removing the first character of the string array and printing out the rest of the string as an int.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, char *argv[])
{
char numcpy1[sizeof(argv[1])-1];
char numcpy2[sizeof(argv[2])-1];
int i, len1, len2;
int result1=0;
int result2=0;
//Access first character for base
printf("%c \n", argv[2][0]);
printf("%c \n", argv[3][0]);
//Remove first character for number1 and number 2
if(strlen(argv[2]) > 0)
{
strcpy(numcpy1, &(argv[2][1]));
}
else
{
strcpy(numcpy1, argv[2]);
}
len1 = strlen(numcpy1);
if(strlen(argv[3]) > 0)
{
strcpy(numcpy2, &(argv[3][1]));
}
else
{
strcpy(numcpy2, argv[3]);
}
len2 = strlen(numcpy2);
//Turn remaining string characters into an int
for(i=0; i<len1; i++)
{
result1 = result1 * 10 + ( numcpy1[i] - '0' );
}
for(i=0; i<len2; i++)
{
result2 = result2 * 10 + ( numcpy2[i] - '0' );
}
printf("%d \n", result1);
printf("%d \n", result2);
return 0;
}
Output:
b
b
-4844
1010
What I want:
b
b
1000
1010
The sizeof operator does not give you the length of a string, as you seem to think it does. It tell you the size of the datatype. Since argv[2] is a char *, this evaluates to the size of this pointer, most likely 4 or 8 depending on the system.
If the string in question is longer than this value, you end up writing past the end of the array. This invokes undefined behavior, which in your case manifests as an unexpected result.
If you want the length of the string, use the strlen function instead. Also, you need to add one more byte. Strings in C are null terminated, so you need space for the null byte that marks the end of the string.
char numcpy1[strlen(argv[2])];
char numcpy2[strlen(argv[3])];
Also note that we don't need to add 1 to each of these since the first character in each string isn't copied.
You need to change
char numcpy1[sizeof(argv[1])-1];
to
char numcpy1[strlen(argv[1]) + 1];
Ditto for numcpy2
I think instead of copying the numbers you could work more easily with pointers. Thereby, you don't have to think about memory allocation and copying the values just for the sake of converting them into an integer value:
const char *numcpy1 = argv[2][0]=='\0' ? argv[2] : argv[2]+1;
...
I have this code:
char kbits[k];
long int bits;
The kbits string is always filled with '1', for example:
If k = 5,
kbits = "11111"
If k = 9,
kbits = "111111111"
To do this I use this code:
for(i = 0; i < k; i++)
kbits[i] = '1';
And then I run:
bits = atoi(kbits);
So I have the integer of kbits, for example, if kbits = "1111", bits = 1111;
For k <= 10, it runs perfectly fine.
For k > 10 it puts a 7 in last position of kbits (for example, if k = 11, kbits = 11111111117) and bits = 2147483647 (this value is for any value of k, I think it is random?)
atoi interprets its input as a decimal number, not a binary number. Your longer string is causing the value to overflow, in which case the return value of atoi is undefined (although returning INT_MAX is common, which is equal to the value you're seeing).
To interpret the input as a binary number you can use strtol like this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
int main()
{
char line[256];
while (printf("\nInput: "),
fgets(line, sizeof line, stdin))
{
// skip initial whitespace and break if input is nothing but whitespace
char *p = line;
while (isspace(*p)) ++p;
if (*p == '\0') break;
// interpret input as a binary number
long n = strtol(line, &p, 2);
if (p == line)
printf("** Can't convert any characters. **\n");
else if (n == LONG_MAX || n == LONG_MIN)
printf("** Range error **\n");
else
printf("Value: %ld\n", n); // prints value in decimal
while (isspace(*p)) ++p; // skip whitespace after the value
if (*p != '\0')
printf("** Excess characters in input **\n");
}
return 0;
}
Your input is too large for the return type. Per the docs:
If the converted value cannot be represented, the behavior is undefined.
An int is a signed type of at least 16-bits. On your platform it may be 32-bits and, in that case, its max value is 2^31-1. Too small for your input of ~11 billion. Use strtol, which returns a long int, instead.
Also, make sure you're terminating that string.
2147483647 (this value is for any value of k, I think it is random?)
No, it is not random; it is the largest value a signed 32-bit integer can hold.
Your inputs are too big.
When this happens, the return value of atoi is undefined (per the documentation); the result you're seeing is common in practice.
Define kbits to be one byte longer then the number of 1s you want to store and do initialise it to all 0s.
#define K (5)
char kbits[K + 1] = ""; /* One more for the `0`temrination neseccary to terminate a C-"string". */
Problem in C programming
I have following list:
int a[] = {0,0,1,0,0,1,0,2}
How do i convert following list items to char variable b?
Like this:
printf(%c, b)
OUTPUT: 00100102
I need this for printing the values of list in embedded system lcd screen where normal print options aren't available. Couldn't find similar example from www.stackoverflow.com. Vice versa there were many solutions to convert a string into a list.
#include <stdio.h>
#include <stdlib.h>
int main(){
int a[] = {0,0,1,0,0,1,0,2};
const char *table = "0123456789";
size_t size = sizeof(a)/sizeof(*a);
char *b = malloc(size+1);
int i;
for(i=0;i<size;++i)
b[i]=table[a[i]];
b[i]='\0';
printf("%s\n", b);
free(b);
return 0;
}
int a = [0,0,1,0,0,1,0,2]
That is not valid C. Perhaps you meant:
const int a[] = { 0, 0, 1, 0, 0, 1, 0, 2 };
Converting a decimal digit to a printable character in C is easy, just add '0':
printf("%c", '0' + a[0]);
will print 0.
You can iterate through the elements of your array, and printf() each one, considering it as an offset from '0':
/*
'0' + 0 = '0'
'0' + 1 = '1'
'0' + 2 = '2'
*/
const int a[] = {0,0,1,0,0,1,0,2};
const int count = sizeof(a) / sizeof(a[0]);
int i;
for (i = 0; i < count; i++) {
printf("%c", '0' + a[i]);
}
printf("\n");
When you convert each value in an array of int to a corresponding value in an array of char, you just have an array of char. When you append the null terminator \0 (or 0) to the array of char, it becomes a C string.
int a[] = {0,0,1,0,0,1,0,2}; //use curly braces to assign values to new array.
char b[sizeof(a)/sizeof(a[0])+1];//Accomodates any size of a. note extra space for terminating \0
int i;
//EDIT 5 following lines
b[0]=0; //ensure string is null terminated
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
sprintf(b, "%s%d", b, a[i]);//copy one char per loop to concatenate string with all elements of `a`
}
Now you have a string, sized according to number of array elements in a that looks like:
"00100102"
In memory you would see |48|48|49|48|48|49|48|50|0|
(the integer values of each character representation of the integers 0, 1, & 2, with the null character 0 in the last position to mark the end of string.)
Note also, the phrase sizeof(array)/sizeof(array[0]) is used to get the number of elements in an array.
I want know how integers are treated in char arrays. For example when we use scanf() & printf() functions for single characters we use "%c", for string values "%s", etc. I used "%s" for printing the char array with integers. But it prints some junk characters as the output.
While working with integer variables directly, it's simple as:
int i = 7;
printf("%d", i);
and while working with an array of characters, you could create helper functions that will do the conversion between char* <-> int so that you end up with more portable solution:
int toInt(unsigned char* p) {
return *(p + 0) << 24 | *(p + 1) << 16 | *(p + 2) << 8 | *(p + 3);
}
...
unsigned char arr[4] = {0,0,0,4};
int i = toInt(&arr[0]);
printf("%d", i);
should print 4
Alternatively you might use simple cast:
unsigned char arr[4] = {0,0,0,4};
int* i = &arr[0];
printf("%d", *i);
but that solution will be depend on endianness. On ideone.com it prints 67108864.
If you know the length of each phone number will be the same, you could pad out the front of the number with zeros. e.g. to pad each number out to 10 digits, putting 0's in front when necessary:
int d = 123456789;
printf("%d\n", d); // prints 123456789
printf("%010d\n", d); // prints 0123456789
d = 12345678;
printf("%010d\n", d); // prints 0012345678 :-(
It's hard to guess more about the requirements without seeing the code. There's lots of examples of formatting with printf, eg: http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output