简体   繁体   中英

C++ code meaning and conversion in Java

I have in C++

char *s, mask;
// Some code

If(*s == 0){ //Some more code}

If(*s & mask){ //Some code}

In Java can I write this like

byte s,mask;
//Some code 
If(s == (byte)0x0){ //Some more code}   
If((s & mask) != (byte)0x0){ //Some Code} 

Is the java code correct?

In C++ the default value of an uninitialized pointers in undefined. You have to initialize it explicitly. In Java, the default value of a variable of type byte is 0 , unless it is a local variable, in which case you have to initialize it explicitly too.

Does the C++ code really say if (*s == 0) , or does it really say if (s == 0) ? In the first, you're checking if what s points to is 0, while in the second, you're checking if s is a null pointer. Those are two very different things.

Java doesn't have pointers, so this code cannot be translated to Java directly.

In C++ this code is undefined behavior:

If(*s == 0)  // 's' is not initialized

I think in Java, eclipse type of editor might complain for uninitialized s . It's a good practice to initialize a variable in any of the language before reading it.

The most likely translation you'd want to do (this looks like some kind of lowlevel parsing; for scanning of binary byte arrays, 'unsigned char' would have been expected):

byte[] s; // with some kind of value
for (int i=0; i<s.Length; i++)
{
     if (s[i] == 0x0){ //Some more code}   
     if ((s[i] & mask) != 0x0){ //Some Code}
}

( untouched by compilees, and my java is swamped by years of C++ and C# :) )

this should be equivalent to your C++ code:

    byte s[], mask;

    if (s[0] == 0) { /*Some more code*/ }

    if ((s[0] & mask) != 0) {/*Some code*/}

@sehe pointed out s is likely to get incremented in the C++ code -- in which case s[0] should change to s[pos] in the Java example:

    byte s[], mask;
    // initialize s[] to store enough bytes
    int pos;
    if (s[pos = 0] == 0) { pos++; /* Some code */ }

    if ((s[pos] & mask) != 0) {/*Some code*/}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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