Converting an integer value to bits and storing it in a char array?

I am developing reliable data transmission over UDP, where in the UDP data buffer, which is an array of characters, and in my first two bytes I have to put bits like 00010000 .... and so on, and I want to know how to achieve this. Please let me know if you need any information in advance for your help, I really appreciate it.

+3
source share
3 answers

write the function of converting numbers to a string (array of characters) steps: 1. Divide the integer by 2 and save the value of the module in the array of characters. 2. print the value of the quotient with an integer and save the result in the same integer 3. continue to do steps 1 and 2 until the integer value becomes zero.

Hope this will be a simple conversion program

+1
source

You ask: "How to convert int-stream [u] to a byte string?"

Then you can try the following:

1. Pick next integer x = uint[i]
2. Get four bytes out of it as
 b4 = x & 0xFF000000
 b3 = x & 0x00FF0000
 b2 = x & 0x0000FF00
 b1 = x & 0x000000FF
3. Write the four bytes into the stream s, e.g.
 s << b4 << b3 << b2 << b1;
4. i += 1
5. Go to 1
+1
source

or use a more general function to write one bit to the buffer (char array) `

void setBitAt( char* buf, int bufByteSize, int bitPosition, bool value )
{
    if(bitPosition < sizeof(char)*8*bufByteSize)
    {
        int byteOffset= bitPosition/8;
        int bitOffset = bitPosition - byteOffset*8;

        if(value == true)
        {
             buf[byteOffset] |=  (1 << bitOffset);
        }
        else
        {
             buf[byteOffset] &= ~(1 << bitOffset);;
        }
    }
}

`

0
source

Source: https://habr.com/ru/post/1735689/


All Articles