1

I am doing networking programming in C\C++ and the assignment asks me to send a formatted message.

The format is below:

bits:    0.....15 16....31  
          update#  port#           
             Sever-IP

As you seen first line ask me to:

  1. Convert int into 16 bits so 2 ints make up 32 bits.

  2. Convert xxx.xxx.xxx.xxx into 32 bits.

I am using UDP, so I need get these info into a char[], and that is the hard part. In my program, I have the update# and port # as int, and server IP address as a string. How could I convert them into these bits?

Here is what I have tried:

  1. Casting them into char. But, I need get one int into two char.

  2. Convert them into a string, and then string.c_str(), but it gives me a 4 bytes pointer.

4

2 回答 2

2

The easiest way to do this is to create a struct for your header like this:

#pragma pack(push,1)

struct header
{
    unsigned short updateNumber;
    unsigned short port;
    unsigned long ip;
};
#pragma pack(pop)

And use it like this:

char *buffer = new char[sizeof(header)+sizeOfRemainingMessage];
header *head = (header*)buffer;
head->update = 1;
head->port = 80;
head->ip = // convert ip string to unsigned long*
send(buffer); 

*To convert the ip string to the unsigned long refer to inet_addr().

于 2012-04-26T02:09:14.227 回答
0

An int or long int in C++ is 4 bytes (32 bits), but it can depend on the implementation. Check the sizes of your types with the sizeof operator.

You can then put the update and port values in it, one after the other, with the use of the shift operators.

For the string it is basically the same thing: You have to break it into four segments, convert each of them into an integer, and shift each segment of the right amount inside a long int.

于 2012-04-26T00:28:16.320 回答