为什么 memcmp return 有正差时为负值?
Why does memcmp return a negative value when there is a positive difference?
#include <stdio.h>
#include <string.h>
int main()
{
int test1 = 8410092; // 0x8053EC
int test2 = 8404974; // 0x803FEE
char *t1 = ( char*) &test1;
char *t2 = (char*) &test2;
int ret2 = memcmp(t1,t2,4);
printf("%d",ret2);
}
这是一个非常基本的函数,当 运行 打印 -2 时。也许我完全误解了 memcmp,但我认为如果它 returns 第一个不同字节之间的差异。由于test1比test2大,打印出来的值不应该是正数吗?
我正在为 ubuntu 使用标准的 gcc.7 编译器。
memcmp
比较内存。也就是说,它比较用于表示对象的字节。用于表示对象的字节可能因 C 实现而异。根据 C 2018 6.2.6 2:
Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number,
order, and encoding of which are either explicitly specified or implementation-defined.
要比较对象表示的值,使用普通运算符<
、<=
、>
、>=
、==
和 !=
。将对象的内存与memcmp
进行比较应该用于有限的目的,例如将对象插入到只需要能够存储和检索项目而不关心什么的树中他们的价值观意味着。
正如评论中指出的那样,memcmp()
运行字节比较。这是一个男人的引述
int memcmp(const void *s1, const void *s2, size_t n);
RETURN VALUE:
The memcmp() function returns an integer less than, equal to, or
greater than zero if the first n bytes of s1 is found, respectively,
to be less than, to match, or be greater than the first n bytes of
s2
For a nonzero return value, the sign is determined by the sign of the
difference between the first pair of bytes (interpreted as unsigned
char) that differ in s1 and s2.
If n is zero, the return value is zero.
http://man7.org/linux/man-pages/man3/memcmp.3.html
如果字节不同,差异的符号取决于目标字节序。
memcmp()
的一个应用是测试两个大数组是否相同,这可能比编写逐个元素比较的循环更快。有关详细信息,请参阅此堆栈问题。 Why is memcmp so much faster than a for loop check?
#include <stdio.h>
#include <string.h>
int main()
{
int test1 = 8410092; // 0x8053EC
int test2 = 8404974; // 0x803FEE
char *t1 = ( char*) &test1;
char *t2 = (char*) &test2;
int ret2 = memcmp(t1,t2,4);
printf("%d",ret2);
}
这是一个非常基本的函数,当 运行 打印 -2 时。也许我完全误解了 memcmp,但我认为如果它 returns 第一个不同字节之间的差异。由于test1比test2大,打印出来的值不应该是正数吗?
我正在为 ubuntu 使用标准的 gcc.7 编译器。
memcmp
比较内存。也就是说,它比较用于表示对象的字节。用于表示对象的字节可能因 C 实现而异。根据 C 2018 6.2.6 2:
Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined.
要比较对象表示的值,使用普通运算符<
、<=
、>
、>=
、==
和 !=
。将对象的内存与memcmp
进行比较应该用于有限的目的,例如将对象插入到只需要能够存储和检索项目而不关心什么的树中他们的价值观意味着。
正如评论中指出的那样,memcmp()
运行字节比较。这是一个男人的引述
int memcmp(const void *s1, const void *s2, size_t n);
RETURN VALUE: The memcmp() function returns an integer less than, equal to, or greater than zero if the first n bytes of s1 is found, respectively, to be less than, to match, or be greater than the first n bytes of s2 For a nonzero return value, the sign is determined by the sign of the difference between the first pair of bytes (interpreted as unsigned char) that differ in s1 and s2. If n is zero, the return value is zero. http://man7.org/linux/man-pages/man3/memcmp.3.html
如果字节不同,差异的符号取决于目标字节序。
memcmp()
的一个应用是测试两个大数组是否相同,这可能比编写逐个元素比较的循环更快。有关详细信息,请参阅此堆栈问题。 Why is memcmp so much faster than a for loop check?