PDA

View Full Version : Storing 8 bit unsigned integers in 1 byte


kushalkoolwal
10-18-2004, 09:10 AM
Hi,

I have a peculiar problem. I want to store a 8-bit unsigned integer (like 2,4,6,8,10,12,14,etc) in packet of 1 byte. How can I do that? Also if I am able to store how can I read that byte agian?

I am giving a sample packet discription as below: How can store number like 2 or 10 in the message type.


0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|message type|
+-+-+-+-+-+-+-+



It would be great if someone can show me a small example.

Thank you

Kushal

RobSeace
10-18-2004, 12:46 PM
I'm not quite sure I understand the problem... An 8-bit unsigned int
will easily fit into a single byte, so I'm not quite sure what you're
asking for... You just assign the value to the byte, and read it from
it... No special work needed... Eg:


char buf[1024]; /* or whatever size */
uint8_t val;

/* val gets set somehow; now, just assign it to first byte of buffer */
buf[0] = val;

/* presumably you want to fill the buffer with some other data... */

write (sockfd, buf, sizeof (buf));


If you wanted to be more correct, you could use an "unsigned char"
buffer rather than a plain "char" buffer, but it really doesn't matter,
as long as you read it back out into a uint8_t (or "unsigned char")
variable at the other end, anyway...

kushalkoolwal
10-18-2004, 06:56 PM
Thanks, actually I got a bit confused in that question.

Will write more if there is any further doubt.

Thank you once again.