I am making my first parallel application, but I am stuck with basics of C. I need to know, how to cast int to char and then how to append one char to another.
It you could help me please, i would be glad. Thank you.
You can use itoa function to convert the integer to a string.
You can use strcat function to append characters in a string at the end of another string.
If you want to convert a integer to a character, just do the following -
int a = 65;
char c = (char) a;
Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).
To do a light reading about type conversion, go here.
If you are still having trouble, comment on this answer.
Edit
Go here for a more suitable example of joining characters.
Also some more useful link is given below -
http://www.cplusplus.com/reference/clibrary/cstring/strncat/
http://www.cplusplus.com/reference/clibrary/cstring/strcat/
Second Edit
char msg[200];
int msgLength;
char rankString[200];
........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id
strncat( msg, rankString, (200 - msgLength) ); // msg now contains previous msg + id
// You may loose some portion of id if message length + id string length is greater than 200
Third Edit
Go to this link. Here you will find an implementation of itoa. Use that instead.
Casting int to char is done simply by assigning with the type in parenthesis:
int i = 65535;
char c = (char)i;
Note: I thought that you might be losing data (as in the example), because the type sizes are different.
Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h> functions like strcat or sprintf.
Casting int to char involves losing data and the compiler will probably warn you.
Extracting a particular byte from an int sounds more reasonable and can be done like this:
number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */
int myInt = 65;
char myChar = (char)myInt; // myChar should now be the letter A
char[20] myString = {0}; // make an empty string.
myString[0] = myChar;
myString[1] = myChar; // Now myString is "AA"
This should all be found in any intro to C book, or by some basic online searching.
int i = 100;
char c = (char)i;
There is no way to append one char to another. But you can create an array of chars and use it.
Related
I'm trying to convert a hexadecimal INT to a char so I could convert it into a binary to count the number of ones in it. Here's my function to convert it into char:
#include <stdio.h>
#include <stdlib.h>
#define shift(a) a=a<<5
#define parity_even(a) a = a+0x11
#define add_msb(a) a = a + 8000
void count_ones(int hex){
char *s = malloc(2);
sprintf(s, "0x%x", hex);
free(s);
printf("%x", s);
};
int main() {
int a = 0x01B9;
shift(a);
parity_even(a);
count_ones(a);
return 0;
}
Every time I run this, i always get different outputs but the first three hex number are always the same. Example of outputs:
8c0ba2a0
fc3b92a0
4500a2a0
d27e82a0
c15d62a0
What exactly is happening here? I allocated 2 bytes for the char since my hex int is 2 bytes.
It's too long to write a comment so here goes:
I'm trying to convert a hexadecimal INT
int are stored as a group of value, padding (possible empty) and sign bits, so is there no such thing as a hexadecimal INT but you can represent (print) a given number in the hexadecimal format.
convert a ... INT to a char
That would be lossy conversion as an int might have 4 bytes of data that you are trying to cram into a 1 byte. char specifically may be signed or unsigned. You probably mean string (generic term) or char [] (standard way to represent a string in C).
binary to count the number of ones
That's the real issue you are trying to solve and this is a duplicate of:
How to count the number of set bits in a 32-bit integer?
count number of ones in a given integer using only << >> + | & ^ ~ ! =
To address the question you ask:
Need to allocate more than 2 bytes. Specifically ceil(log16(hex)) + 2 (for 0x) + 1 (for trailing '\0').
One way to get the size is to just ask snprintf(s, 0, ...)
then allocate a suitable array via malloc (see first implementation below) or use stack allocated variable length array (VLA).
You can use INT_MAX instead of hex to get an upper
bound. log16(INT_MAX) <= CHAR_BIT * sizeof(int) / 4 and the
latter is a compile time constant. This means you can allocate your string on stack (see 2nd implementation below).
It's undefined behavior to use a variable after it's deallocated. Move free() to after the last use.
Here is one of the dynamic versions mentioned above:
void count_ones(unsigned hex) {
char *s = NULL;
size_t n = snprintf(s, 0, "0x%x", hex) + 1;
s = malloc(n);
if(!s) return; // memory could not be allocated
snprintf(s, n, "0x%x", hex);
printf("%s (size = %zu)", s, n);
free(s);
};
Note, I initialized s to NULL which would cause the first call to snprintf() to return an undefined value on SUSv2 (legacy). It's well defined on c99 and later. The output is:
0x3731 (size = 7)
And the compile-time version using a fixed upper bound:
#include <limits.h>
// compile-time
void count_ones(unsigned hex) {
char s[BIT_CHAR * sizeof(int) / 4 + 3];
sprintf(s, "0x%x", hex);
printf("%s (size = %zu)", s, n);
};
and the output is:
0x3731 (size = 11)
Your biggest problem is that malloc isn't allocating enough. As Barmar said, you need at least 7 bytes to store it or you could calculate the amount needed. Another problem is that you are freeing it and then using it. It is only one line after the free that you use it again, which shouldn't have anything bad happen like 99.9% of the time, but you should always free after you know you are done using it.
I am creating a simple encryption program.
I am adding chars to chars to create a new char.
As of now the new 'char' is often a represented by a '?'.
My assumption was that the char variable has a max sum and once it was passed it looped back to 0.
assumed logic:
if char a == 1 && char z == 255
then 256 should == a.
This does not apear to be the case.
This snippet adds a char to a char.
It often prints out something like:
for (int i = 0; i < half; ++i) {
halfM1[i] = halfM1[i] + halfP1[i];
halfM2[i] = halfM2[i] + halfP2[(half + i)];
}
printf("\n%s\n", halfM1 );
printf("%s\n", halfM2);
Returns:
a???
3d??
This snippet removes the added char and the strings go back to normal.
for (int i = 0; i < half; ++i) {
halfM1[i] = halfM1[i] - halfP1[i];
halfM2[i] = halfM2[i] - halfP2[(half + i)];
}
printf("\n%s\n", halfM1 );
printf("%s\n", halfM2);
returns:
messagepart1
messagepart2
The code technically works, but I would like the encryption to be in chars.
If question on why 'half' is everywhere.
The message and key are split in half so the first half and second half of message have separate encryption.
First of all, there is no such thing as "wraparound" for common char. A common char is a signed type in x86, and signed integers do not have wraparound. Instead the overflow leads to undefined behaviour. Additionally, the range of chars can be -128 ... 127, or even something
For cryptographic purposes you'd want to use unsigned chars, or even better, raw octets with uint8_t (<stdint.h>).
Second problem is that you're printing with %s. One of the possible 256 resulting characters is \0. If this gets into the resulting string, it will terminate the string prematurely. Instead of using %s, you should output it with fwrite(halfM1, buffer_size, 1, stdout). Of course the problem is that the output is still some binary garbage. For this purposes many Unix encryption programs will write to file, or have an option to output an ASCII-armoured file. A simple ASCII armouring would be to output as hex instead of binary.
The third is that there is an operation that is much better than addition/subtraction for cryptographic purposes: XOR, or halfM1[i] = halfM1[i] ^ halfP1[i]; - the beauty of which is that it is its own inverse!
I need to do a RPC. I'm trying to encode the length of a function name followed by the name of the function.
Function name: say_hello
Function name length: 9
Encoded array: [9, 's', 'a', 'y', ..., 'l', 'l', 'o']
So far:
unsigned char* encode_int(unsigned char *buffer, int value) {
buffer[0] = value >> 24;
buffer[1] = value >> 16;
buffer[2] = value >> 8;
buffer[3] = value;
return buffer + 4;
}
char* function_name = "say_hello";
char* buffer[256];
buffer = encode_int(&buffer, strlen(function_name));
strcpy(buffer, function, strlen(function_name));
puts(buffer);
You have lots of problems with your code. I won't just give you a working solution but will point out the problems. The first thing is that the code obviously doesn't compile. You are passing an undefined variable function to strcpy and give too many arguments to strcpy. I'll assume you've just transcribed the program incorrectly. But even if you fix that you will get a few compiler warnings which, if heeded, would identify most of your problems.
You are passing the address of buffer rather than the buffer itself to encode_int.
You declare buffer as an array of char pointers. Looks like what you really want is an array of char.
You encode an int into the start of the buffer. And then you try to print it as a string (via puts). That's not going to work and will result in no output (as you have probably found). Because the int will have a 0 value in the first byte (as you have encoded it). This is a null terminator for a string and hence the blank output.
EDIT: Correction to point 3. You've actually incremented buffer by 4 (if everyting else was fixed). So the puts will only show the function name (again, if everything else was fixed). And you've effectively lost the function name length.
Put words into buffer like this
int len;
len=Strlen(word);
memcpy(buffer,&len,sizeof(Int));
strncpy (&buffer[sizeof (int)],word,len);
Change the puts line to read
printf("%d %s\n",buffer,&buffer[sizeof (int)]);
I'm not good in C, top of that I'm doing after very long, I need to do a very simple thing:
char code[]="aasd";
char *rmessage="";
strcat(rmessage,code[0]);
I simply want to concatenate the content of index 0 of array code to rmessage.
You need to ensure there is enough space in rmessage to store the result of the concatentation. You can use strncat to specify the number of characters to copy from a string:
char code[] = "aasd";
char rmessage[1024] = "";
strncat(rmessage, code, 1);
or, in this case, just assign the first character of rmessage:
rmessage[0] = code[0];
Not coding in C for long time.I think the syntax is just correct.
int sz=10; // sz = # number of chars you want to store + 1 , i assumed 9 characters will be stored at max.
char code[] = "aasd";
char *rmessage = malloc(sz*sizeof(char));
rmessage[0]=code[0];
rmessage[1]=NULL;
*Remember to deallocate the memory allocated to rmessage after your job is done.
free(rmessage);
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];