将两个整数作为一个整数传递 [英] Pass two integers as one integer

查看:79
本文介绍了将两个整数作为一个整数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个整数,我需要先传递一个整数,然后再取回两个整数的值.

I have two integers that I need to pass through one integer and then get the values of two integers back.

我正在考虑使用逻辑运算符(AND,OR,XOR等).

I am thinking of using Logic Operators (AND, OR, XOR, etc) .

推荐答案

使用C编程语言,可以假定两个整数小于65535,可以按如下方式进行操作.

Using the C programming language, it could be done as follows assuming that the two integers are less than 65535.

void take2IntegersAsOne(int x)
{
   // int1 is stored in the bottom half of x, so take just that part.
   int int1 = x & 0xFFFF;  

   // int2 is stored in the top half of x, so slide that part of the number
   // into the bottom half, and take just that part.
   int int2 = (x >> 16) & 0xFFFF

   // use int1 and int2 here. They must both be less than 0xFFFF or 65535 in decimal

}


void pass2()
{
  int int1 = 345;
  int int2 = 2342;
  take2Integers( int1 | (int2 << 16) );
}

这依赖于以下事实:在C中,一个整数存储在4个字节中.因此,该示例使用前两个字节存储整数之一,然后使用第二个字节存储第二个整数.尽管每个整数必须具有足够小的值,以便每个整数只能容纳2个字节,但这确实施加了限制.

This relies on the fact that in C an integer is stored in 4 bytes. So, the example uses the first two bytes to store one of the integers, and the next two bytes for the second. This does impose the limit though that each of the integers must have a small enough value so that they will each fit into just 2 bytes.

移位运算符<<和>>用于向上和向下滑动整数的位.移位16,将位移动两个字节(因为每个字节有8位).

The shift operators << and >> are used to slide the bits of an integer up and down. Shifting by 16, moves the bits by two bytes (as there are 8 bits per byte).

使用0xFFFF表示该位模式,其中该数字的后两个字节中的所有位均为1s.因此,ANDing(与&运算符一起使用)会导致所有不在这两个后两个字节中的位都被关闭(返回零).这可用于从当前正在提取的部分中删除其他整数"的任何部分.

Using 0xFFFF represents the bit pattern where all of the bits in the lower two bytes of the number are 1s So, ANDing (with with & operator) causes all the bits that are not in these bottom two bytes to be switched off (back to zero). This can be used to remove any parts of the 'other integer' from the one you're currently extracting.

这篇关于将两个整数作为一个整数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆