Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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 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 info, thanks in advance for your help, I really appreciate it

like image 200
Ragy Avatar asked Sep 16 '26 10:09

Ragy


2 Answers

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

like image 193
abubacker Avatar answered Sep 19 '26 02:09

abubacker


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
like image 32
Arun Avatar answered Sep 19 '26 02:09

Arun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!