3

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

Fmstrat
  • 1,492
  • 2
  • 17
  • 24
  • 2
    I *hope* you're not thinking that the string "1234" (0x31323334) is in any way equivalent to the binary character array "0x01020304". Just checking ;) – paulsm4 Sep 24 '12 at 02:19
  • See http://stackoverflow.com/questions/7021725/converting-string-to-integer-c – szx Sep 24 '12 at 02:50

3 Answers3

5

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).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

I think its simply

plainchar = (char*)plaintext;
sscanf( plainchar, "%d", &plainint );
Sodved
  • 8,428
  • 2
  • 31
  • 43
1

for unsigned char to char*

plainchar = (char*)plaintext;

for unsigned to int

sscanf( plainchar, "%d", &plainint );
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70
  • check your encryption algorithm – Ravindra Bagale Sep 24 '12 at 03:08
  • @BenCurtis: Update your question rather than using comments. – Jonathan Leffler Sep 24 '12 at 03:08
  • Thanks (and to @Sodved), except this doesn't create expected results for me. For some reason, if plaintext is "AAAAAA123456" and I do the above, plainchar is now equal to "AAAA123456" and sizeof reports 51. Thoughts? – Fmstrat Sep 24 '12 at 03:19
  • @BenCurtis Surely you meant `strlen` reports 51? `sizeof` only cares about the _type_ of its argument, `sizeof plainchar` is the size of a `char*`, regardless of what the contents of `plaintext` are. – Daniel Fischer Sep 24 '12 at 13:07