Fmstrat
Fmstrat

Reputation: 1692

Unsigned char to char* and int in C?

Working on some encryption that requires unsigned char's in the functions, but want to convert to a char for use after it's been decrypted. So, I have:

unsigned char plaintext[16];
char *plainchar;
int plainint;

... Code now populates plaintext with data that happens to all be plain text

Now at this point, let's say plaintext is actually a data string of "0123456789". How can I get the value of plaintext into plainchar as "012456789", and at the same time plainint as 123456789?

-- Edit --

Doing this when plaintext is equal to "AAAAAAAAAA105450":

unsigned char plaintext[16];
char *plainchar;
int plainint;

... Code now populates plaintext with data that happens to all be plain text

plainchar = (char*)plaintext;

Makes plainchar equal to "AAAAAAAAAA105450╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠┤∙7" with a sizeof = 51. The encryption code is the rijndael example code, so it should be working fine.

Thanks, Ben

Upvotes: 3

Views: 4061

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409196

Your plain text string is not terminated. All strings must have an extra character that tells the end of the string. This character is '\0'.

Declare the plaintext variable as

unsigned char plaintext[17];

and after you are done with the decryption add this

plaintext[last_pos] = '\0';

Change last_pos to the last position of the decrypted text, default to 16 (last index of the array).

Upvotes: 5

Ravindra Bagale
Ravindra Bagale

Reputation: 17655

for unsigned char to char*

plainchar = (char*)plaintext;

for unsigned to int

sscanf( plainchar, "%d", &plainint );

Upvotes: 1

Sodved
Sodved

Reputation: 8588

I think its simply

plainchar = (char*)plaintext;
sscanf( plainchar, "%d", &plainint );

Upvotes: 1

Related Questions