菜鸟教程小白 发表于 2022-12-13 07:26:18

ios - 打破一个 32bit 整数,并使用后半部分 16bit 形成一个 int


                                            <p><p>我正在制作一个从服务器下载 32 位整数的应用,并将第一个 16 位和第二个 16 位用于不同目的...</p>

<p>我负责第二个16bit,应该用来形成一个int,我知道我应该使用按位运算来做到这一点,但无法实现,下面是我正在使用的代码,请给我更多信息.</p>

<pre><code>      //CID is a 32bit integer, in nslog it shows as 68913219 - its different for every user
      Byte lowByte = (CID&gt;&gt;16)&amp;0xFF; //the 3rd byte
      Byte highByte = (CID&gt;&gt;24)&amp;0xFF; //the 4th byte
      uint16_t value = lowByte &amp; highByte; //combine, but the result is 0.
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><pre><code>uint16_t value = lowByte &amp; highByte; //combine, but the result is 0.
</code></pre>

<p>这不是您将两个字节组合成一个 <code>uint16_t</code> 的方式:您是在对它们进行 <code>AND</code> 操作,而您需要移动高字节,并且 <code>OR</code> 它与低字节:</p>

<pre><code>uint16_t value = lowByte | (((uint16_t)highByte) &lt;&lt; 8);
</code></pre>

<p>然而,这在可读性方面不是最理想的:如果你从一个 32 位整数开始,并且你需要去掉高 16 位,你可以简单地移位 16,并用 <code>0xFFFF</code> - 即与剪切第三个字节的方式相同,但使用 16 位掩码。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 打破一个 32bit 整数,并使用后半部分 16bit 形成一个 int,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/22853583/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/22853583/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 打破一个 32bit 整数,并使用后半部分 16bit 形成一个 int