Given a char, how to convert this char to a two digit char, which is the hex value of the binary presentation?
For example, given a char, it has a binary presentation, which is one byte, for example, 01010100, which is 0x54.....I need the char array of 54.
Actually it would be:
char c = 84;
char result[3];
sprintf(result,"%02x",c);
This is all far to easy readable :-)
#define H(x) '0' + (x) + ((x)>9) * 7
char c = 84;
char result[3] = { H(c>>4), H(c&15) };
The following code, using snprintf() should work:
#include <stdio.h>
#include <string.h>
int main()
{
char myChar = 'A'; // A = 0x41 = 65
char myHex[3];
snprintf(myHex, 2 "%02x", myChar);
// Print the contents of myHex
printf("myHex = %s\n", myHex);
}
snprintf() is a function that works like printf(), except that it fills a char array with maximum N characters. The syntax of snprintf() is:
int snprintf(char *str, size_t size, const char *format, ...)
Where str is the string to "sprint" to, size is the maximum number of characters to write (in our case, 2), and the rest is like the normal printf()
Related
I am trying to compare two set of data using strcmp. This first set of data are var1 which is get from fgets(var1, 100, stdin). The second set of data are generate randomly by rand. When I complie it, I get two same errors. They both come from char f.
warning: assignment makes pointer from integer without a cast printf(f);
warning:assignment makes pointer from integer without a cast if (strcmp(var1,f)==0)
i already declare the randomly generated number char f = rand() % 38; in char, why will it not work?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char var1[100];
int result;
fgets(var1, 100, stdin);
srand(time(NULL));
char myArray[38] = { 1,5,3,4};
char f = rand() % 38;
printf(var1);
printf(f);
if (strcmp(var1,f)==0) {
result = 1;
printf("It work\n");
}
else {
printf("It didn't work!\n");
result = 0;
}
return 0;
}
EDITED CODE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char var1[100];
int result;
scanf("%s",var1);
srand(time(NULL));
char myArray[7] = { 0,28,9,26,30,11,7 };
int randomindex= 1 + (rand() % 100);
char f = myArray[randomindex];
char str_f[2] = { f, '\0' };
printf("var1: %s\n",var1);
printf("%s",str_f);
printf("\n");
if (strcmp(var1,str_f)==0) {
result = 1;
printf("It work\n");
}
else {
printf("It didn't work!\n");
result = 0;
}
return 0;
}
As commented above, in C Langage, functions from Library have a strict format and using not that expected format will occur warning or error at compilation time or runtime.
Function 1 - the printf() is the common function to write C strings to the standard output stdout (declared in <stdio.h>).
See the C library function - printf()
int printf(const char *format, ...)
In the provided source code, the printf() function has been used in the following cases:
printf("It work\n"); to write a fixed string which complies with the const char * expected format of the first parameter ==> OK,
printf(var1); to write the content of the entered string var1 (declared as char var1[100];) which not exactly complies with const char * of the first parameter but will be cast during compile time. A proposed format to write the var1 string could be printf("%s",var1); (or more verbose printf("var1: %s",var1);) where the first parameter "%s" will specify that the following argument var1 will be a string.
printf(f); to write the content of the random value (declared as char f;) which doesn't comply with const char * of the first parameter and doesn't compile at all. The minimal expected format to write the f character is printf("%c",f); (or more verbose printf("f=%c",f);) where the first parameter "%c" will specify that the following argument f will be a character.
Function 2 - the strcmp() is a function to compare two C strings parameters (declared in <string.h>.
See the C library function - strcmp()
int strcmp(const char *str1, const char *str2)
In the provided source code, the strcmp() function has not been used as specified. The function expects two input parameters:
First parameter of strcmp(var1,...)==0 is var1 (declared as char var1[100];) which not exactly complies with const char * but will be cast during compile time.
Second parameter of strcmp(...,f)==0 is f (declared as char f;) which doesn't comply with const char * and doesn't compile at all.
To compare the character f with var1, it shall be necessary to
convert it to a string (In C, a string is an array of char ended by
a character).
Solution 1 - how to convert the character char f; to a string.
A C string is an array of characters: char str_f[]= { '<char>', ... , '<NUL>' };. Meaning that a minimal array of 2 characters is necessary to convert the character char f; to a string.
char f = rand() % 38;
// use a 2 characters string
char str_f[2] = { f, '\0' };
// Could be also initialised as str_f[0] = f; str_f[1] = '\0';
// compare the strings using `str_f`
if (strcmp(var1,str_f)==0) {
Warning 1 - be careful to the random value range.
When printing characters, a C string is supposed to be filled by ASCII
characters different from which is used to end the string.
In the provided source code, the assignment of f, char f = rand() % 38;, will generate values from 0 to 37 which include the character and the first 31 non-printable characters (ctrl-characters). Only characters greater than 31 will be displayed.
In will be more easy to generate: char f = ' ' + (rand() % 38);
where ' ' is the first printable ASCII character = 32.
I have a pointer lpBegin pointing to a string "1234". Now i want this string compare to an uint how can i make this string to unsigned integer without using scanf? I know the string number is 4 characters long.
You will have to use the atoi function. This takes a pointer to a char and returns an int.
const char *str = "1234";
int res = atoi(str); //do something with res
As said by others and something I didn't know, is that atoi is not recommended because it is undefined what happens when a formatting error occurs. So better use strtoul as others have suggested.
Definitely atoi() which is easy to use.
Don't forget to include stdlib.h.
You can use the strtoul() function. strtoul stands for "String to unsigned long":
#include <stdio.h>
#include <stdlib.h>
int main()
{
char lpBegin[] = "1234";
unsigned long val = strtoul(lpBegin, NULL, 10);
printf("The integer is %ul.", val);
return 0;
}
You can find more information here: http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/
You could use strtoul(lpBegin), but this only works with zero-terminated strings.
If you don't want to use stdlib for whatever reason and you're absolutely sure about the target system(s), you could do the number conversion manually.
This one should work on most systems as long as they are using single byte encoding (e.g. Latin, ISO-8859-1, EBCDIC). To make it work with UTF-16, just replace the 'char' with 'wchar_t' (or whatever you need).
unsigned long sum = (lpbegin[0] - '0') * 1000 +
(lpbegin[1] - '0') * 100 +
(lpbegin[2] - '0') * 10 +
(lpbegin[3] - '0');
or for numbers with unknown length:
char* c = lpBegin;
unsigned long sum = 0;
while (*c >= '0' && *c <= '9') {
sum *= 10;
sum += *c - '0';
++c;
}
I think you look for atoi()
http://www.elook.org/programming/c/atoi.html
strtol is better than atoi with better error handling.
You should use the strtoul function, "string to unsigned long". It is found in stdlib.h and has the following prototype:
unsigned long int strtoul (const char * restrict nptr,
char ** restrict endptr,
int base);
nptr is the character string.
endptr is an optional parameter giving the location of where the function stopped reading valid numbers. If you aren't interested of this, pass NULL in this parameter.
base is the number format you expect the string to be in. In other words, 10 for decimal, 16 for hex, 2 for binary and so on.
Example:
#include <stdlib.h>
#include <stdio.h>
int main()
{
const char str[] = "1234random rubbish";
unsigned int i;
const char* endptr;
i = strtoul(str,
(char**)&endptr,
10);
printf("Integer: %u\n", i);
printf("Function stopped when it found: %s\n", endptr);
getchar();
return 0;
}
Regarding atoi().
atoi() internally just calls strtoul with base 10. atoi() is however not recommended, since the C standard does not define what happens when atoi() encounters a format error: atoi() can then possibly crash. It is therefore better practice to always use strtoul() (and the other similar strto... functions).
If you're really certain the string is 4 digits long, and don't want to use any library function (for whatever reason), you can hardcode it:
const char *lpBegin = "1234";
const unsigned int lpInt = 1000 * (lpBegin[0] - '0') +
100 * (lpBegin[1] - '0') +
10 * (lpBegin[2] - '0') +
1 (lpBegin[3] - '0');
Of course, using e.g. strtoul() is vastly superior so if you have the library available, use it.
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.
Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks!
So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:
#define bufferSize 10
int main() {
unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
char converted[bufferSize*2 + 1];
int i;
for(i=0;i<bufferSize;i++) {
sprintf(&converted[i*2], "%02X", buffer[i]);
/* equivalent using snprintf, notice len field keeps reducing
with each pass, to prevent overruns
snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
*/
}
printf("%s\n", converted);
return 0;
}
Which outputs:
0102030405060708090A
In C, a string is an array of char, terminated with a character whose value is 0.
Whether or not char is a signed or unsigned type is not specified by the language, you have to be explicit and use unsigned char or signed char if you really care.
It's not clear what you mean by "representing" an unsigned character array as string. It's easy enough to cast away the sign, if you want to do something like:
const unsigned char abc[] = { 65, 66,67, 0 }; // ASCII values for 'A', 'B', 'C'.
printf("The English alphabet starts out with '%s'\n", (const char *) abc);
This will work, to printf() there isn't much difference, it will see a pointer to an array of characters and interpret them as a string.
Of course, if you're on a system that doesn't use ASCII, there might creep in cases where doing this won't work. Again, your question isn't very clear.
Well a string in C is nothing else than a few chars one after another. If they are unsigned or signed is not much of a problem, you can easily cast them.
So to get a string out of a unsigned char array all you have to do is to make sure that the last byte is a terminating byte '\0' and then cast this array to char * (or copy it into a array of char)
I successfully use this to convert unsigned char array to std:string
unsigned char array[128];
std::stringstream buffer;
for (int i = 0; i < 128; i++)
{
buffer << std::hex << std::setfill('0');
buffer << std::setw(2) << static_cast<unsigned>(array[i]);
}
std::string hexString = buffer.str();
An example as you've asked:
unsigned char arr [SIZE];
I have a simple question
How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?
Thanks
main()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
Hope it will be helpful to you.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;
itoa(a,arr,10) ; // itoa() is a function of stdlib.h file that convert integer
// int to array itoa( integer, targated array, base u want to
//convert like decimal have 10
for( int i= 0 ; i < strlen(arr); i++) // strlen() function in string file thar return string length
printf("%c",arr[i]);
}
Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.
char c[2];
int i=1;
sprintf(c, "%d", i);
If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:
int x;
char c = '0' + x;
Now, if you want a character string, just add a terminating '\0' char:
char s[] = {'0' + x, '\0'};
Note that:
You must be sure that the int is in the 0-9 range, otherwise it will fail,
It works only if character codes for digits are consecutive. This is true in the vast majority of systems, that are ASCII-based, but this is not guaranteed to be true in all cases.
You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...
int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];
Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!
But you probably meant "i want to stringify a number", so ignore this response :-)