JavaBits
JavaBits

Reputation: 2055

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?

Upvotes: 0

Views: 352

Answers (5)

Nick
Nick

Reputation: 5805

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*/}

Upvotes: 0

Jesper
Jesper

Reputation: 206816

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.

Upvotes: 1

Björn Pollex
Björn Pollex

Reputation: 76788

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.

Upvotes: 1

sehe
sehe

Reputation: 392954

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# :))

Upvotes: 0

iammilind
iammilind

Reputation: 69988

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.

Upvotes: 0

Related Questions