i have an unsigned char which i need to convert to char before printf. So the example code goes like this:
unsigned char y = sample.result;
char x = (char)y;
printf("%c \n", x);
However, printf does not print x but if i use cout, x prints correctly.I have no idea why so. How to i convert a unsigned char variable to a char? Am i doing it wrong? reinterpret_casting is only for pointer and mine are not pointers. Thanks in advance.
EDIT: Command prompt returns me a smiley face "☺" for the value of sample.result which corresponds to unsigned char 1. And apparently netbeans is unable to print this smiley face. I have no idea how it got translated into a smiley face. Any help?
EDIT 2: I just realized you can't print char x = 1; in netbeans, and printing it in command prompt yields the smiley face. Reasons? :(
If char x = 1 and you want a 1 to be printed out, you need to use %d instead of %c in your format specifier. %c prints the ASCII representation of the number, which for 1 is an unprintable character called "start of heading."
Try making x an int instead of char and see if that works. C rules required all char parameters to be converted to int, and printf is a C function.
The %c conversion for printf is only for characters in the basic character set. It seems you have an extended character that you want to print, so you'd have to use the appropriate tool for that. The type for that would be wchar_t and the print format %lc. But beware this depends a lot of your execution environment, locale settings and stuff like that.
And BTW in many circumstances narrow types like char are just converted to int or unsigned, so there is no need to cast it, and in fact other than your title suggests your problem has not much to do with casting.
I'm not confident in this answer, but I just wrote a simple test program that compiles and prints the letter A without casting the unsigned char back to a char.
#include <stdio.h>
int main()
{
unsigned char c = 'A';
printf("%c\n",c);
return 0;
}
Casting directly also worked:
#include <stdio.h>
int main()
{
unsigned char c = 'A';
printf("%c\n",(char)c);
return 0;
}
Doing it your way ALSO worked...
#include <stdio.h>
int main()
{
unsigned char c = 'A';
char d = (char)c;
printf("%c\n",d);
return 0;
}
So I assume I'm doing something wrong, now. Or maybe something else is your problem?
Here the equation of conversion
the algorithm for char c to unsigned char uc.
return (c>127) ? (unsigned char)(-(256 + c)) : (unsigned char)c;
the algorithm for unsigned uc to char c.
return (uc < 0) ? (char)(256-(char)abs(uc)) : (char)uc;
Related
I want the result to be the value of ac[0],but it is showing something confusing.The second line works.
#include <stdio.h>
int main(void){
char a='a';
char b='b';
char ac[]={-24,1,2,3,4,5,6,7,8,9,};
char *p=ac;
printf("*p=%c ",*p);//this is the part that produces problem
printf("*p=%d ",*p);//this works
//! *(p+n)<--->ac[n]
}
%c prints the character encoded by integer hold by the char integer value.
The most popular 7 bits system system is ASCII :
(above 0x7f they are not standard).
I was trying to make this int to char program. The +'0' in the do while loop wont convert the int value to ascii, whereas, +'0' in main is converting. I have tried many statements, but it won't work in convert() .
#include<stdio.h>
#include<string.h>
void convert(int input,char s[]);
void reverse(char s[]);
int main()
{
int input;
char string[5];
//prcharf("enter int\n");
printf("enter int\n");
scanf("%d",&input);
convert(input,string);
printf("Converted Input is : %s\n",string);
int i=54;
printf("%c\n",(i+'0')); //This give ascii char value of int
printf("out\n");
}
void convert(int input,char s[])
{
int sign,i=0;
char d;
if((sign=input)<0)
input=-input;
do
{
s[i++]='0'+input%10;//but this gives int only
} while((input/=10)>0);
if(sign<0)
s[i++]='-';
s[i]=EOF;
reverse(s);
}
void reverse(char s[])
{
int i,j;
char temp;
for(i=0,j=strlen(s)-1;i<j;i++,j--)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
Output screenshot
Code screenshot
The +'0' in the do while loop wont convert the int value to ascii
Your own screenshot shows otherwise (assuming an ASCII-based terminal).
Your code printed 56, so it printed the bytes 0x35 and 0x36, so string[0] and string[1] contain 0x35 and 0x36 respectively, and 0x35 and 0x36 are the ASCII encodings of 5 and 6 respectively.
You can also verify this by printing the elements of string individually.
for (int i=0; string[i]; ++i)
printf("%02X ", string[i]);
printf("\n");
I tried your program and it is working for the most part. I get some goofy output because of this line:
s[i]=EOF;
EOF is a negative integer macro that represents "End Of File." Its actual value is implementation defined. It appears what you actually want is a null terminator:
s[i]='\0';
That will remove any goofy characters in the output.
I would also make that string in main a little bigger. No reason we couldn't use something like
char string[12];
I would use a bare minimum of 12 which will cover you to a 32 bit INT_MAX with sign.
EDIT
It appears (based on all the comments) you may be actually trying to make a program that simply outputs characters using numeric ascii values. What the convert function actually does is converts an integer to a string representation of that integer. For example:
int num = 123; /* Integer input */
char str_num[12] = "123"; /* char array output */
convert is basically a manual implementation of itoa.
If you are trying to simply output characters given ascii codes, this is a much simpler program. First, you should understand that this code here is a mis-interpretation of what convert was trying to do:
int i=54;
printf("%c\n",(i+'0'));
The point of adding '0' previously, was to convert single digit integers to their ascii code version. For reference, use this: asciitable. For example if you wanted to convert the integer 4 to a character '4', you would add 4 to '0' which is ascii code 48 to get 52. 52 being the ascii code for the character '4'. To print out the character that is represented by ascii code, the solution is much more straightforward. As others have stated in the comments, char is a essentially a numeric type already. This will give you the desired behavior:
int i = 102 /* The actual ascii value of 'f' */
printf("%c\n", i);
That will work, but to be safe that should be cast to type char. Whether or not this is redundant may be implementation defined. I do believe that sending incorrect types to printf is undefined behavior whether it works in this case or not. Safe version:
printf("%c\n", (char) i);
So you can write the entire program in main since there is no need for the convert function:
int main()
{
/* Make initialization a habit */
int input = 0;
/* Loop through until we get a value between 0-127 */
do {
printf("enter int\n");
scanf("%d",&input);
} while (input < 0 || input > 127);
printf("Converted Input is : %c\n", (char)input);
}
We don't want anything outside of 0-127. char has a range of 256 bits (AKA a byte!) and spans from -127 to 127. If you wanted literal interpretation of higher characters, you could use unsigned char (0-255). This is undesirable on the linux terminal which is likely expecting UTF-8 characters. Values above 127 will be represent portions of multi-byte characters. If you wanted to support this, you will need a char[] and the code will become a lot more complex.
I am trying to use sscanf to convert an array of char in C to a double. My issue is best described in this short minimal working example:
#include <stdio.h>
int main (int argc, char **argv)
{
char string_one[] = "1.2e-4";
char string_two[6] = "1.2e-4";
double one, two;
sscanf(string_one, "%lf", &one);
sscanf(string_two, "%lf", &two);
printf("%e, %e\n", one, two);
return 0;
}
Compiled with GCC and running the resulting executable returns 1.200000e-04, 1.200000e-41, instead of the same number twice. The issue does not appear if the floating point number I want to convert is of the form 3e4(if there is no decimal separator).
For my program I have to define an array of char with a fixed size (as I am filling the array during the course of the program), which is why I am running into this issue.
I guess the problem might be pretty obvious - but as I am a newbie in C I am out of ideas what the problem could be. Any help appreciated!
char string_two[6] = "1.2e-4"; ... sscanf(string_two, "%lf", &two); expects to scan a string. string_two[] is not a string as it lacks a null character. Result: undefined behavior (UB).
Solution: Insure string_two[] is a string.
I have the following piece of code compiling under gcc:
int parseMsg(const char *msg_to_parse, unsigned long *exp_input, unsigned long *sysTicks )
{
int l_msg_size = strlen(msg_to_parse);
if(l_msg_size <10)
return -1;
char l_exp_input_arr[10];
char l_sys_ticks_arr[10];
memcpy(l_sys_ticks_arr,msg_to_parse+12,10);
memcpy(l_exp_input_arr,msg_to_parse,10);
//l_msg_size = strlen(msg_to_parse);
*sysTicks = strtoul(l_sys_ticks_arr,NULL,10);
*exp_input = strtoul(l_exp_input_arr,NULL,10);
return 0;
}
And I'm trying to test it in the following manner:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int parseMsg(const char *msg_to_parse, unsigned long *exp_input, unsigned long *sysTicks );
int main(void) {
char msg[] = "1234567890 59876543213";
unsigned long along1, along2;
along1 =0;
along2=0;
parseMsg(msg,&along1, &along2 );
printf("result of parsing: \n \t Along 1 is %lu \n \t Along 2 is %lu \n",along1, along2);
return 0;
}
But, I'm getting the following result:
result of parsing:
Along 1 is 1234567890
Along 2 is 4294967295
Why is the second unsigned long wrong?
Thanks
The second integer you provide is too big to be represented in memory on your architecture. So, according to its API, strtoul is just returning you ULONG_MAX (=4294967295 on your architecture), along with setting errno to ERANGE
strtoul API is here : http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/
BUT it may also fail if you gave a smaller integer, because strtoul only stops parsing when it encounters a non-numerical character. Since you didn't ensure that, you cannot be sure that strtoul will not try to parse whatever is in memory just after your strings. (So assuming random, you have 10 chance out of 256 to have a conversion error)
Terminate your strings with \0, it will be ok then :
char l_exp_input_arr[11]; // +1 for \0
char l_sys_ticks_arr[11];
memcpy(l_sys_ticks_arr, msg_to_parse+12, 10);
l_sys_ticks_arr[10] = '\0';
memcpy(l_exp_input_arr, msg_to_parse, 10);
l_exp_input_arr[10] = '\0';
You need to make your two temporary char[] variables one char longer and then make the last character NULL.
For some reason my C program is refusing to convert elements of argv into ints, and I can't figure out why.
int main(int argc, char *argv[])
{
fprintf(stdout, "%s\n", argv[1]);
//Make conversions to int
int bufferquesize = (int)argv[1] - '0';
fprintf(stdout, "%d\n", bufferquesize);
}
And this is the output when running ./test 50:
50
-1076276207
I have tried removing the (int), throwing both a * and an & between (int) and argv[1] - the former gave me a 5 but not 50, but the latter gave me an output similar to the one above. Removing the - '0' operation doesn't help much. I also tried making a char first = argv[1] and using first for the conversion instead, and this weirdly enough gave me a 17 regardless of input.
I'm extremely confused. What is going on?
Try using atoi(argv[1]) ("ascii to int").
argv[1] is a char * not a char you can't convert a char * to an int. If you want to change the first character in argv[1] to an int you can do.
int i = (int)(argv[1][0] - '0');
I just wrote this
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv) {
printf("%s\n", argv[1]);
int i = (int)(argv[1][0] - '0');
printf("%d\n", i);
return 0;
}
and ran it like this
./testargv 1243
and got
1243
1
You are just trying to convert a char* to int, which of course doesn't make much sense. You probably need to do it like:
int bufferquesize = 0;
for (int i = 0; argv[1][i] != '\0'; ++i) {
bufferquesize *= 10; bufferquesize += argv[1][i] - '0';
}
This assumes, however, that your char* ends with '\0', which it should, but probably doesn't have to do.
(type) exists to cast types - to change the way a program looks a piece of memory. Specifically, it reads the byte encoding of the character '5' and transfers it to memory. A char* is an array of chars, and chars are one byte unsigned integers. argv[1] points to the first character. Check here for a quick explanation of pointers in C. So your "string" is represented in memory as:
['5']['0']
when you cast
int i = (int) *argv[1]
you're only casting the first element to an int, thus why you
The function you're looking for is either atoi() as mentioned by Scott Hunter, or strtol(), which I prefer because of its error detecting behaviour.