移位n位字符的整个阵列 [英] Shift N bits an entire array of chars

查看:175
本文介绍了移位n位字符的整个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有字符数组,我想N位左移每个字节,携带到左边,所以才有了第一个字符的N位将会丢失。

Let's say I have an array of chars and I want to shift N bits to the left each byte, carrying to the left, so only the N bits of the first character would be lost.

例如: kxmo 转向3位向左应该成为 X @ HX

Example: kxmo shifted 3 bits to the left should become X@hx

这是我现在,但预计它不工作:

This is what I have currently, but it's not working as expected:

#include <stdio.h>

int main(void) {
    //shift the array with length *len* *shift* bits to the left
    int len = 4, shift = 3;
    unsigned char a[len] = "kxmo";
    unsigned char b[len]; //X@hx

    unsigned char tmp = 0, tmp2 = 0;
    for(int i = len - 1; i > 0; i--) {
        tmp = 0 | (a[i] << shift);
        b[i] = a[i];

        tmp2 = 0 | (a[i - 1] << shift);
        b[i - 1] = (a[i - 1] << shift) ^ tmp;
    }

    printf("old: %s | new: %s\n", a, b);

    return 0;
}

我在哪里失败?

编辑:

这是我得到现在:老:kxmo |新:XMO

推荐答案

如何类似的东西(假设0℃= &LT; 8):

How about something like that (assuming 0 <= shift < 8):

#define BITS_IN_BYTE 8
for(int i = len - 1; i > 0; i--) 
{
    b[i] = a[i] << shift;
    b[i - 1] = (a[i - 1] << shift) | (a[i] >> (BITS_IN_BYTE - shift));
}

我没有检查,但我希望它会做你想要的。

I didn't check it but I hope it will do what you want.

修改

好吧,我检查,它确实你所期望的。

OK, I checked and it does what you expect.

请注意 - >你需要code> LEN 设置<5,而不是4 '\\ 0'。还注意到,在第一次迭代( B [I] = A [1] - ;&LT;移; )将在完成'\\ 0 但是因为它的值是0,这是确定。

NOTE --> you need to set len to 5 and not to 4 for '\0'. also note that the first iteration (b[i] = a[i] << shift;) will be done on the '\0' but since its value is 0, it is OK.

这篇关于移位n位字符的整个阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆