简体   繁体   中英

Memory allocation in C vs Java

I am trying to find if a number is even or odd without using Modulus operation. According to my understanding, when I define an int in C or in Java, that number is stored as 64 bytes of memory. I can access Zeroth(0th) bit of that number using square bracket[].

However, I am not able to do it in Java.

So, my question is how memory allocation and syntax is different in Java?

This really is nothing to do with "memory" or "memory allocation". You're talking about a simple property of a number.

In binary, the least significant bit of a number is 1 if the number is odd, or 0 if the number is even. OK, so how do we isolate the bottom bit? The answer is the 'and' operation, expressed in both C and Java as '&'.

  boolean isEven = (number & 1) == 0;  
  boolean isOdd = (number & 1) != 0;  

By the way, in C

  • An integer certainly does not occupy 64 bytes. Maybe 64 bits, depending on computer, C implementation, etc.

  • Given a single integer, brackets don't give you bit-level access. Brackets are for array indexing: ie, picking out the N'th number in an array of numbers.

You cannot access memory in Java like you can in C

You can, however, use the bit wise & operator to pick out one or more bits of the integer value. If you do it for the bit corresponding to even/odd and see if the result is zero or not, you will have your answer without using modulo

You can't access individual bits in an integer type in C or Java using the [] operator. The operand of the [] operator must be an array type (C and Java) or a pointer type (C).

Integer types in C and Java behave similarly, although integer types in Java have a fixed size (C integer types have a minimum size). In both languages, integer types are allocated the same way.

As for testing odd/even integers without using bitwise operations (which may have endianness issues) or the modulus operator, you can take advantage of integer arithmetic.

In both C and Java, dividing an integer by an integer gives an integer result. 3/2 == 1 , not 1.5 . 100/26 == 3 , etc. So, if you divide the original value by 2, then multiply that result by 2, you'll get the original value back only if the original value is even:

3 / 2 == 1, 1 * 2 == 2, 2 != 3 
4 / 2 == 2, 2 * 2 == 4, 4 == 4
5 / 2 == 2, 2 * 2 == 4, 4 != 5

You get the idea. So,

int tmp = x / 2;
if ( x == tmp * 2 )
  // x is even
else
  // x is odd

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