You can use the "%.*s"
format specifier:
printf("Test: %.*s", bufSize, decrypted);
which instructs printf()
to write the first bufSize
characters from decrypted
.
Frage
I have the following code (I stripped down the useless parts):
unsigned char* decrypted= (unsigned char *) malloc(500);
bufSize = operations.RSADecrypt(newEncrypted, bufSize, key, decrypted);
printf("Test: %s", decrypted);
And I would like to display only the bufSize
first characters of decrypted
because actually it displays a lot of nonsense characters!
Lösung
You can use the "%.*s"
format specifier:
printf("Test: %.*s", bufSize, decrypted);
which instructs printf()
to write the first bufSize
characters from decrypted
.
Andere Tipps
You can limit the length with the format specifier:
printf ("Test: %-20.20s", decrypted);
For a version using a variable bufSize
:
printf ("Test: %-*.*s", bufSize, bufSize, decrypted);
Note that this forces the length to exactly that many characters, padded with spaces on the right if need be. If you want a shorter string to be shorter in the output (irrelebant in your case if the string is, as indicated, always longer than what you want output), you can use:
printf ("Test: %.*s", bufSize, decrypted);
If you are 'allowed' to modify the decrypted
string. You can simply add a terminator to it:
decrypted[bufSize] = 0;
So printf()
will only print the buffer contents.
If you are not allowed to add a custom char to the decrypted
buffer you need to copy the contents to a temporary buffer and use that buffer in your printf()
:
unsigned char* tmp = (unsigned char *) malloc(bufSize + 1);
strncpy(tmp, decrypted, bufSize);
tmp[bufSize] = 0;
I don't like that you said the pointer contained nonsense. Its not nonsense, its residual memory. There is a good chance you expect and want this area to be set to zero. Try the following, where calloc
sets the malloc
bits to zero.
unsigned char* decrypted= (unsigned char *) calloc(500,sizeof(char));
bufSize = operations.RSADecrypt(newEncrypted, bufSize, key, decrypted);
printf("Test: %s", decrypted);