函数实现:
信息来自RHEL,man page:
MEMCMP(3) Linux Programmer's Manual MEMCMP(3)
NAME
memcmp - compare memory areas
SYNOPSIS
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);
DESCRIPTION
The memcmp() function compares the first n bytes (each interpreted as
unsigned char) of the memory areas s1 and s2.
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.
memcpy()函数实现:
0.函数原型:
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);
1.参数:
s1:指向要比较的内存区域指针1。
s2:指向要比较的内存区域指针2。
n:要比较的前n个字节。
2.返回值:
逐字节比较两内存区域数据,当遇到第一个不相等的字节区时,返回:
当
s1
所指向当前区域数据大于s2
时:返回大于0
的值。
当s1
所指向当前区域数据等于s2
时:返回等于0
的值。
当s1
所指向当前区域数据小于s2
时:返回小于0
的值。
3.功能描述:
memcmp函数实现内存比较,类比于strcmp:传送门:http://blog.csdn.net/riyadh_linux/article/details/50021381,:
返回值区别在于:
strcmp返回ASCII码差值;
memcmp返回的为位数(是相同情况下strcmp256倍。->自己理解如有偏差,算我说错^_^);memcmp函数会逐字节比较s1和s2所指内存区,
s1 > s2 —-> 返回 >0 的值
s1 = s2 —-> 返回 =0 的值
s1 < s2 —-> 返回 <0 的值
4.实现:
#define UNIT (256)
#define FALSE (('z' - 'A') * UNIT)
int my_memcmp(const void *s1, const void *s2, size_t n)
{
unsigned char *s1_func = (char *)s1;
unsigned char *s2_func = (char *)s2;
//参数判断
if(NULL == s1_func || NULL == s2_func || 0 > n){
return FALSE;
}
//比较
while(n-- && *(s1_func) == *(s2_func)){
s1_func++;
s2_func++;
}
return ((*s1_func - *s2_func)*UNIT);
}
=============文章结束==============
小菜总结,如有不当,欢迎批评!