简体   繁体   中英

Char* and byte* equality comparison (numbers and text)

I have the following a char* key which is a char array that can contain either integers or text. So the key can have value 3 or tom for example

I have a byte* data array which contains stored data. I need to test whether the key is equal to the data.

My logic is currently along the lines of:

int j = 0 ;
for (j = 0; j < len; j++) {
    sprintf(key_cmp, "%02x", (ulong)*data++);
}
if (!strcmp(key, key_cmp)) fprintf(stderr, "Equal \n");

I realise this code is incorrect as i am trying to print as hex rather than char here... but when I try to use %02x, garbage gets printed out.

How can I also ensure that 01 and 1 will be treated as equal? I realise that this may vary on byte ordering, hence I can't think of a general solution. I'd like to avoid using atoi so was wondering if there was another method (mostly because I have no real way of knowing whether the key is an integer or not)

Thanks

The guess is your problem is that %02x is the format for an int not a unsigned long - so you're on system where sizeof(int)!=sizeof(long) that will cause a problem.

See [Wiki][1] for a description of format specifiers.

Because char[] is 1 byte and byte[] is 1 byte it would be easier to compare them as byte arrays (unsigned char). Either will do the same thing without any special formatting.

memcmp(key,data,len)
strcmp(key,data,len)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM