简体   繁体   English

位操作,保存位,8位后扩展

[英]bit operations, save bits, expand after 8 bits

I want to traverse a binary tree from the bottom to the top. 我想从底部到顶部遍历二叉树。

Then i want to save the bitsequence of this traversion(=the way) in a char. 然后我想将此遍历的位序列(=方式)保存在一个字符中。

This behaviour should be dynamic, so if i have a bitsequence of more than 8 bits, the char should be dynamically expanded, for example, 2 bytes and so on.... 此行为应是动态的,因此,如果我的位序列大于8位,则应动态扩展char,例如2个字节,等等。

If the bitsequence is for example 1001010 i want that exact same bitsequence stored inside the char. 例如,如果位序列是1001010,则我希望该完全相同的位序列存储在char中。

I know that i should use the bitshift operators << >> but i can't quite figure out the correct way to do it. 我知道我应该使用移位运算符<< >>,但是我还不太清楚这样做的正确方法。

After i wrote 8 bits in the char i encounter a problem. 在char中写了8位之后,我遇到了问题。

I attached some sample code, hopefully somebody can shed some light. 我附上了一些示例代码,希望有人能有所启发。

Thanks 谢谢

char* bits = malloc(sizeof(char));
char* temp_bits = NULL;

some loop
{
  if (cnt_bit > 7)
  {
    temp_bits = realloc(bits, sizeof(char)*2);
    free(bits);
    bits = temp_bits;
  }
  *bits = *bits << 1;
  *bits = *bits | 0;
  cnt_bit++;
}

You can't shift from one memory value to the next! 您不能从一个内存值转移到另一个! If you want to do that you could try to use the type "long long int" which is 64 bit normally but i don't think you can go further than that with shifts, unless you implement your own shift operation which works on a generic array. 如果您想这样做,可以尝试使用通常为64位的“ long long int”类型,但是我不认为您可以更进一步地进行移位,除非您实现自己的可在通用类型上使用的移位操作数组。

I think what you are doing would be much faster by using one byte per level. 我认为通过每个级别使用一个字节,您正在做的事情会更快。

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

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