memcmp函数实现——string.h库函数


函数实现:


信息来自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);
}

=============文章结束==============
小菜总结,如有不当,欢迎批评!

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值