简体   繁体   English

字符*和字节*相等性比较(数字和文本)

[英]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. 我有以下一个char *键,它是一个可以包含整数或文本的char数组。 So the key can have value 3 or tom for example 因此,例如,键的值可以为3或tom

I have a byte* data array which contains stored data. 我有一个byte *数据数组,其中包含存储的数据。 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. 我意识到这段代码是不正确的,因为我试图在此处打印为十六进制而不是char……但是当我尝试使用%02x时,会打印出垃圾。

How can I also ensure that 01 and 1 will be treated as equal? 我还如何确保01和1相等? 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) 我想避免使用atoi,所以想知道是否还有另一种方法(主要是因为我没有知道键是否为整数的真正方法)

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. 猜测是您的问题是%02xint的格式,而不是unsigned long %02x因此您在系统上,其中sizeof(int)!=sizeof(long)会引起问题。

See [Wiki][1] for a description of format specifiers. 有关格式说明符的描述,请参见[Wiki] [1]。

Because char[] is 1 byte and byte[] is 1 byte it would be easier to compare them as byte arrays (unsigned char). 因为char []是1个字节,byte []是1个字节,所以将它们比较为字节数组(无符号char)会更容易。 Either will do the same thing without any special formatting. 无需任何特殊格式即可执行相同的操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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