开发者

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

开发者 https://www.devze.com 2022-12-21 22:26 出处:网络
I am designing a Reliable data transmission over UDP, where in the UDP data buffer which is a character array and in my first 2 bytes of it I ha开发者_如何转开发ve to put bits like 00010000.... and so

I am designing a Reliable data transmission over UDP, where in the UDP data buffer which is a character array and in my first 2 bytes of it I ha开发者_如何转开发ve 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 info, thanks in advance for your help, I really appreciate it


write a function of converting a numbers into an string ( character array ) steps : 1.divide a integer number by 2 and store the modulus value in a character array. 2.subtract the quotient value with an integer and store the result in the same integer 3. keep on doing the step 1 and 2 until the integer value becomes zero.

Hope that this would be the simple conversion program


Are you asking, "How to convert an [u]int-stream into a byte-string?"

Then you can try this:

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


or use more generic function to write a single bit into 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

精彩评论

暂无评论...
验证码 换一张
取 消