您将每个字节的两个半字节设置为相同的值,因为您最终将高半字节设置为与低半字节相同。我假设这是一个错误,您的意图是移动数据中的所有半字节,从一个字节传送到另一个字节,然后滚动。Id est,ABCDEF(从低到高的半字节顺序)将变为 FABCDE。如果我弄错了,请纠正我。
代码应该是这样的:
static void crypt_enc(char *data, int size)
{
char last = 0;
//...
// Pass 2
for (i = 0; i < size; i++)
{
nibles *n = (nibles *)&data[i];
unsigned char old_low = n->low;
n->low = last;
last = n->high;
n->high = old_low;
}
((nibles *)&data[0])->low = last;
}
现在一切都好吗?不,只有当 的对齐不比 的对齐更严格时,转换nibbles*
为才被明确定义。这并不能保证(但是,只需稍加更改,GCC 就会生成具有相同对齐方式的类型)。nibbles
char
就个人而言,我会完全避免这个问题。这是我的做法:
void set_low_nibble(char& c, unsigned char nibble) {
// assumes nibble has no bits set in the four higher bits)
unsigned char& b = reinterpret_cast<unsigned char&>(c);
b = (b & 0xF0) | nibble;
}
void set_high_nibble(char& c, unsigned char nibble) {
unsigned char& b = reinterpret_cast<unsigned char&>(c);
b = (b & 0x0F) | (nibble << 4);
}
unsigned char get_low_nibble(unsigned char c) {
return c & 0x0F;
}
unsigned char get_high_nibble(unsigned char c) {
return (c & 0xF0) >> 4;
}
static void crypt_enc(char *data, int size)
{
char last;
//...
// Pass 2
for (i = 0; i < size; ++i)
{
unsigned char old_low = get_low_nibble(data[i]);
set_low_nibble(data[i], last);
last = get_high_nibble(data[i]);
set_high_nibble(data[i], old_low);
}
set_low_nibble(data[0], last);
}
反向操作相当于将“低”变为“高”,反之亦然;滚动到最后一口,而不是第一口;并以相反的方向浏览数据:
for (i = size-1; i >= 0; --i)
{
unsigned char old_high = get_high_nibble(data[i]);
set_high_nibble(data[i], last);
last = get_low_nibble(data[i]);
set_low_nibble(data[i], old_high);
}
set_high_nibble(data[size-1], last);
如果你愿意,你可以摆脱所有转移到临时的last
。您只需要保存最后一个半字节,然后直接移动半字节而不使用另一个变量:
last = get_high_nibble(data[size-1]);
for (i = size-1; i > 0; --i) // the last one needs special care
{
set_high_nibble(data[i], get_low_nibble(data[i]));
set_low_nibble(data[i], get_high_nibble(data[i-1]));
}
set_high_nibble(data[0], get_low_nibble(data[0]));
set_low_nibble(data[0], last);