开发者

Using 1 int to send 2 numbers

开发者 https://www.devze.com 2023-02-17 01:01 出处:网络
I am working with a system whereby I can send 1 32 bit int at a time.However I need to send two numbers at a time.What is the best way to do this in standard C?

I am working with a system whereby I can send 1 32 bit int at a time. However I need to send two numbers at a time. What is the best way to do this in standard C?

I assume I will have to do some conversion to binary/hex a开发者_运维技巧nd some masking?

Any ideas would be appreciated.

Thanks


You can encode two 16-bit unsigned numbers like this:

unsigned int out = (in1 << 16) | in2;

and decode them like this:

unsigned int in1 = out >> 16;
unsigned int in2 = out & 0xFFFF;

All this assumes that int is at least 32 bits, that in1 and in2 are in the 0-65535 range, and that an unsigned int can be sent across correctly (w.r.t. endianness).


If the numbers you are sending are between 0 and 65535 each just pack them in the 32-bit int you can send:

unsigned int n1 = 42;
unsigned int n2 = 1600;
unsigned int numbertosend = (n1 << 16) | n2;

On the receiving side, unpack the number

unsigned int n1 = receivednumber >> 16;
unsigned int n2 = receivednumber & 0xFFFF;


What range are your numbers? If they can fit in 16 bits, then you can pack two of those in your 32 bit int. Something like i = (n1 << 16) | (n2 &0xffff).


You could encode 2 16-bit numbers into a 32-bit number. For example:

int32 encode(int16 numA, int16 numb) {
    int 32 result = numA << 16 | numB;
    return  result;
}

int16 decodeNum1(int32 num) {
    return (num >> 16) & 0xFFFF;
}

int16 decodeNum2(int32 num) {
    return (num) & 0xFFFF;
}


If the two numbers you want to send are both prime, you could multiply them and send the product, and on the server factor them to get the result.

;p (inspired by the ambiguity in the question)


Assuming you want to send 2 16-bit numbers, you could probably do something like this:

unsigned int a, b, toSend;
// Give a and b a value...
toSend = ( a << 16 ) | b;


I think Unions in c would do the job.You could also go for Bit Fields in C

0

精彩评论

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

关注公众号