I am trying to depict what this java print statement “ (((0xFF << (i * 8)) & test)))) “ means

-2

My assignment is to figure out what this java program written by my teacher is doing, without running it. I have attached the whole (short) program and bolded the expression I do not understand. It is apart of the first for loop, which I am also a little unclear as to what it does.

import java.util.*;
int intSize = Integer.SIZE / 8; char storage[] = new char[intSize]; int test = 0xffffffff,
 test2 = 0; 

System.out.println(String.format("0x%08x",0xFF << (3 * 8) & test));
storage[0] = (char) ((0xF << 4));

for (int i = intSize - 1 ; i > -1 ; i--)
// storage[i] = (char) ((0xFF << (i * 8)) & test);
     System.out.println(String.format("0x%08x",**(((0xFF << (i * 8)) & test))));** 
for (int i = 0, j = intSize-1; i < intSize ; i++, j--)
     test2 &= (((int) storage[i]) << (j * 8));
System.out.println(“The Magic Word of the Day is the English word for: ”+test2);
java
function
loops
asked on Stack Overflow Mar 19, 2020 by griffin3419

1 Answer

-1

A useful way to analyze what code is doing, is to break it down into the smallest possible steps.

First, there are extra parentheses which are not needed. So let’s clean that up, by changing this:

(((0xFF << (i * 8)) & test))

to this, which is exactly the same thing:

(0xFF << (i * 8)) & test

Now, imagine it broken down into separate steps:

int value = i * 8;
int mask = 0xFF << value;
int result = mask & test;

So, you know that:

  • value is a multiple of 8
  • mask is eight contiguous 1 bits (because 0xFF is 11111111 in base two), shifted by a count which is a multiple of 8
  • result is the application of that mask to the 32 bits 11111111111111111111111111111111 (which is the base two form of 0xffffffff, which is the value of test)

Hopefully, if you’ve been given this assignment, you already understand the purpose of the bitwise & operator: each 1-bit in one operand preserves the corresponding bit in the other operand, while 0-bits in either operand are always cleared in the result.

There a lot of things in this code which are poor practice. Not challenging, just bad. You’ve been given an assignment which is much harder than it should be, in my opinion, for the purpose of demonstrating knowledge of Java’s mathematical and bitwise operators.

answered on Stack Overflow Mar 19, 2020 by VGR

User contributions licensed under CC BY-SA 3.0