This is the code, I have, i cover the message into hex-representation in string, but after second times covering, the m1_hex accidentally become empty string
#include <stdio.h>
#include <string.h>
#include <openssl/bn.h>
typedef unsigned char text;
typedef const size_t slen;
void turnCharToHexString(text *pt, text *ht, slen size){
for(size_t i = 0, j = 0; i < size; i, j =2){
sprintf(ht j, "x", pt[i] & 0xff);
}
printf("The msg %s in hex is %s\n", pt, ht);
}
int main(){
text* m1 = "I owe you $2000.";
text* m2 = "I owe you $3000.";
slen sm1 = strlen(m1);
text m1_hex[sm1 * 2];
text m2_hex[sm1 * 2];
turnCharToHexString(m1, m1_hex, sm1);
printf("what is m1_hex (1): '%s'\n", m1_hex);
turnCharToHexString(m2, m2_hex, sm1);
printf("what is m1_hex (2): '%s'\n", m1_hex);
printf("what is m2_hex (1): '%s'\n", m2_hex);
exit(EXIT_SUCCESS);
}
This is the output, what is m1_hex (2) prints empty string, even I didnt modify anything
the output:
The msg I owe you $2000. in hex is 49206f776520796f752024323030302e
what is m1_hex (1): '49206f776520796f752024323030302e'
The msg I owe you $3000. in hex is 49206f776520796f752024333030302e
what is m1_hex (2): '' //disappear
what is m2_hex (1): '49206f776520796f752024333030302e'
CodePudding user response:
Change:
text m1_hex[sm1 * 2 1];
text m2_hex[sm1 * 2 1];
As the comments have mentioned, this is becuase the null terminator,
check this post here sprintf() without trailing null space in C
There is no way to tell sprintf() not to write a trailing null. What you can do is use sprintf() to write to a temporary string, and then something like strncpy() to copy only the bytes that you want.
You may have that string temporarily there, but the following scanf will discard the previous store.