移植C $ C $℃;需要位运算和指针的语法帮助 [英] Porting C code; need help with bitwise operation and pointer syntax

查看:167
本文介绍了移植C $ C $℃;需要位运算和指针的语法帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些C code,我想移植到Java的。我没有做过太多C编写中,但我能跟着,直到这一功能。如果有人可以帮助我明白是怎么回事,这将是极大的AP preciated。

  INT reverse_integer(INT输入){
    INT输出= 0,I;    对于(i = 0,I<的sizeof(int);在我++){
         输出=(输入和放大器; 0x000000FF)|输出;
         输入>> = 8;
         如果(ⅰ3;){
             输出与所述;&下; = 8;
         }
    }    返回输出;
}

该函数被用作这样:

 的char *位置= //一些数据/ *在这个在下一行所包含的评论指出字符串的大小* /
INT I = reverse_integer(*为(int *)的位置)


解决方案

我会很高兴发布的Java code,做一样的C code,但只有当你承诺不使用它

 / **反转一个整数,字节。 * /
   公共静态INT reverseInteger(INT输入){
      返回
         (输入>>> 24)|
         (输入>→8)&0x0000ff00 |
         (输入<< 8)0x00ff0000 |
         (输入<< 24);
   }

请注意,有一个在循环没有意义 - 一个 INT 在Java中始终是4个字节。还要注意在开始三右尖括号除权pression执行无符号右移。

现在的理由不使用它:

1 - 该功能已经存在 - 看看 Integer.reverseBytes(INT)

2 - 你将不得不使用例如code很难,因为Java并不让你施放的字节数组作为别的。 Java是正式大端(最显著字节在前),因此,如果您从文件中读取字节,那么你可以使用 java.io.DataInputStream中来提取的int,long等等。

I have some C code that I'd like to port to java. I haven't done much C coding, but I was able to follow along up until this one function. If anyone could help me understand what is going on, it would be greatly appreciated.

int reverse_integer(int input) {
    int output = 0, i;

    for ( i=0, i<sizeof(int); i++ ) {
         output = ( input & 0x000000FF ) | output; 
         input >>= 8;
         if ( i < 3 ) {
             output <<= 8;
         }
    }

    return output;
}

The function is used as such:

char * position = //some data

/*the included comment on this next line states its the size of a string*/
int i = reverse_integer( *(int*)position )

解决方案

I'll be happy to post Java code that does the same as the C code, but only if you promise not to use it.

/** Reverses the bytes in an integer. */
   public static int reverseInteger(int input) {
      return
         (input >>> 24) |
         (input >> 8) & 0x0000ff00 |
         (input << 8) & 0x00ff0000 |
         (input << 24);
   }

Note that there's no point in looping - an int in Java is always 4 bytes. Also note the triple-right angle bracket at the beginning the expression to perform an unsigned right-shift.

Now for the reasons not to use it:

1 - The function already exists - see Integer.reverseBytes(int)

2 - You're going to have a hard time using that example code, since Java doesn't let you cast an array of bytes as anything else. Java is officially big-endian (most significant byte first), so if you're reading bytes from a file then you can use java.io.DataInputStream to extract ints, longs, etc.

这篇关于移植C $ C $℃;需要位运算和指针的语法帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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