繁体   English   中英

子字符串— C内联汇编代码

[英]substring — c inline assembly code

我编写了一个代码,该代码使用gcc内联汇编获取字符串的子字符串。 但是当我想要获取长度为8的子字符串时,总会遇到问题。这是代码

static inline char * asm_sub_str(char *dest, char *src, int s_idx, int edix)
{
    __asm__ __volatile__("cld\n\t"
                         "rep\n\t"
                         "movsb"
                         :
                         :"S"(src + s_idx), "D"(dest), "c"(edix - s_idx + 1)
                         );
    return dest;
}

int main(int argc, char *argv[])
{

    char my_string[STRINGSIZE] = "abc defghij";
    char asm_my_sub_string[STRINGSIZE];

    int sidx,eidx;

    sidx = 0;
    eidx = 5;
    char *d1 = asm_sub_str(asm_my_sub_string, my_string, sidx, eidx);
    printf("d1[%d-%d]: %s\n",sidx, eidx, d1);

    sidx = 0;
    eidx = 7;
    d1 = asm_sub_str(asm_my_sub_string, my_string, sidx, eidx);
    printf("d1[%d-%d]: %s\n",sidx, eidx, d1);

    sidx = 0;
    eidx = 9;
    d1 = asm_sub_str(asm_my_sub_string, my_string, sidx, eidx);
    printf("d1[%d-%d]: %s\n",sidx, eidx, d1);

}

这是输出

d1[0-5]: abc de
d1[0-7]: abc defg?
d1[0-9]: abc defghi

任何想法?????

谢谢您的回复。 这是子字符串的c代码,我忘记了以null终止字符串。 感谢仙人掌和bbonev! 希望其他人可以从该主题中学到。

static inline char * sub_str(char *dest, char *src, int s_idx, int edix)
{
    int length = edix - s_idx + 1;
    int i;

    for(i = 0; i < length; i++)
    {
        *(dest + i) = *(src + s_idx + i);
    }
    *(dest + length) = '\0';

    return dest;
}

我想它不起作用,因为汇编代码不为0终止结果缓冲区。

我总是更喜欢带有起始位置和计数而不是两个位置的子字符串语义。 人们认为这样简单。

无需从该函数返回任何值。

static inline void asm_sub_str(char *dest, char *src, int s_idx, int count)
{
    __asm__ __volatile__("cld\n"
                         "rep\n"
                         "movsb\n"
                         "xor %%al,%%al\n"
                         "stosb\n"
                         :
                         :"S"(src + s_idx), "D"(dest), "c"(count)
                         );
}

编辑:请注意,尽管此实现是用汇编编写的,但它不是最理想的。 对于特定的体系结构,内存对齐和字长对于提高速度很重要,可能最好的复制方法是对齐机器大小的字。 首先一个字地复制最多字大小为1个字节,然后以字为单位复制字符串的大部分,最后完成最后一个字大小为1个字节的操作。

我认为这个问题是内联汇编和传递参数时的最佳选择,而不是复制字符串的最佳方法。 对于现代C编译器,期望使用-O2可以更快地生成代码。

暂无
暂无

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

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