简体   繁体   English

将按位操作从C#移植到C

[英]Porting Bitwise Operations from C# To C

I need some help porting this C# code over to C. I have it working in C# just fine but I'm getting the wrong return in C. Should I be breaking down the bit shifting into separate lines? 我需要一些帮助将这个C#代码移植到C.我已经在C#中工作了很好但是我在C中得到了错误的返回。我应该将这个位分解成单独的行吗? I thought I had an issue with the data types but I think I have the right ones. 我以为我的数据类型有问题,但我认为我有正确的数据类型。 Here was the working code that returns 0x03046ABE 这是返回0x03046ABE的工作代码

  UInt32 goHigh(UInt32 x) { return (UInt32)(x & 0xFFFF0000); }          
  UInt32 goLow(UInt32 x) { return (UInt32)(x & 0xFFFF); } 

  UInt32 magic(UInt32 pass){
      UInt32 key = pass;
      UInt16 num = 0x0563;
      key = (goLow(key) << 16) | (UInt16)(((num >> 3) | (num << 13)) ^ (goHigh(key) >> 16));
      return key; //returns 0x03046ABE

   }

  magic(0x01020304);

This was the incorrect C code that I'm trying to get working 这是我正在努力工作的错误C代码

  unsigned long  goHigh(unsigned long  x) { 
         return (unsigned long )(x & 0xFFFF0000); }          
  unsigned long  goLow(unsigned long  x) { 
         return (unsigned long )(x & 0xFFFF); } 

  unsigned long  magic(unsigned long  pass){
      unsigned long key = pass;
      unsigned int num = 0x0563;
      key = (goLow(key) << 16) | (unsigned int)(((num >> 3) | (num << 13)) ^ (goHigh(key) >> 16));
      return key;
  }

  magic(0x01020304); //returns 0xb8c6a8e

Most likely problem is here: 最有可能的问题是:

key = (goLow(key) << 16) | (unsigned int)(((num >> 3) | (num << 13)) ^ (goHigh(key) >> 16));
                            ^^^^^^^^^^^^

which you expect is 16-bit. 你期望的是16位。 It may be larger on different machines. 它可能在不同的机器上更大。 Same with unsigned long, which may be 64-bit instead of 32, as you expect. 与无符号长整数相同,可能是64位而不是32,正如您所期望的那样。

To be sure, use uint32_t & uint16_t . 当然,请使用uint32_tuint16_t You have to #include <stdint.h> to be able to use them. 你必须#include <stdint.h>才能使用它们。

long and int are not the sizes you expect on your platform (32 and 16 bits respectively) long和int不是您在平台上预期的大小(分别为32位和16位)

Replace the primitive types with the actual sizes and it will be the same output. 将原始类型替换为实际大小,它将是相同的输出。 I've also removed redundant casts. 我也删除了多余的演员阵容。

These types can be found in stdint.h 这些类型可以在stdint.h中找到

#include <stdint.h>

    uint32_t  goHigh(uint32_t   x) {
        return (x & 0xFFFF0000);
    }

    uint32_t goLow(uint32_t x) {
        return (x & 0xFFFF);
    }

    uint32_t magic(uint32_t pass) {
        uint32_t  key = pass;
        uint32_t num = 0x0563;
        key = (goLow(key) << 16) | (uint16_t)(((num >> 3) | (num << 13)) ^ (goHigh(key) >> 16));
        return key;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM