简体   繁体   中英

C++ write a number on two bytes

I am new to the low level c++, and I find it a bit hard to understand how to manipulate bits. I am trying to do the following to use in a compression algorithm I am trying to make:

unsigned int num = ...;//we want to store this number
unsigned int num_size = 3;//this is the maximum size of the number in bits, and
//can be anything from 1 bit to 32

unsigned int pos = 7;//the starting pos on the 1st bit.
//this can be anything from 1 to 8

char a;
char b;

if the num_size is 3 and pos is 7 for example, we must store num , on the 7th and 8th bit of a and on the 1st bit of b .

How about just?

a = num << (pos-1);
b = ((num << (pos-1)) & 0xFF00) >> 8;

To read num back just

num = ((unsigned int)a + ((unsigned int b) << 8)) >> (pos - 1);

Note, this doesn't do any sanity checks, such as whether all the relevant bits fit in a and b, you'll have to do that yourself.

For this specific test case, the highest number that fits into 2 unsigned char is actually 65535 .

#include <iostream>

unsigned char high(int input)
{
    return (input >> 8) & 0xFF;
}

unsigned char low(int input)
{
    return input & 0xFF;
}

int value(unsigned char low, unsigned char high)
{
    return low | (high << 8);
}

int main()
{
    int num = 65535;
    unsigned char l = low(num);
    unsigned char h = high(num);

    int val = value(l, h);
    std::cout<<"l: "<<l<<" h: "<<h<<"  val: "<<val;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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