Search code examples
c++printfunsigned-char

Display the first characters of an unsigned char*


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!


Solution

  • You can use the "%.*s" format specifier:

    printf("Test: %.*s", bufSize, decrypted);
    

    which instructs printf() to write the first bufSize characters from decrypted.