Reputation: 5852
I need to figure out, how to set the hexa number 0xffff, which is used for bitwise AND in code below dynamically.
int offsetData = address & 0xffff;
For example I need something like this:
int offsetData = address & myHexaValue;
I have a decimal int value, which I need to put in hexadecimal format instead of myHexaValue.
This is my state now.
int decimalShift = 16*8;
String myHexaValueString = Integer.toHexString(decimalShift);
Now.. can I convert my String hexa number to int hexa number so I could put result into myHexaValue?
Upvotes: 1
Views: 1620
Reputation: 425033
Use Integer.parseInt()
, specifying a radix of 16
:
int number = Integer.parseInt(myHexaNumber, 16);
Upvotes: 1
Reputation: 811
You don't need to convert it. There is no such thing as a hex number. A number written in hex is a number written in a base 16 notation. We normally use base 10 notation so we have digits from 0 to 9 but in hex notation you have digits from 0 to F. So just do a and operation :
int offsetData = address & decimalShift;
EDIT: To get only the lower 16 bit use a mask. 0xffff and perform a & operation the upper 16 bits will be set to 0 and the lower 16 will remain unchanged. so:
int offsetData = address & decimalShift & 0xffff;
EDIT2: To get a mask for any number(0,...,31) of bits you can use this function:
private static int getMask(int numOfOnes) {
int i = 0x80000000;
i = i>>(32-numOfOnes-1);
i = ~i;
return i;
}
Pauls explanation: "bitshifting with >> fills the most signifcant bits with the value of the MSB before shifting, so in this code all bits except for the numOfOnes lowest bits are filled with 1s and afterwards the number is inverted."
Upvotes: 2
Reputation:
Numbers aren't "hexadecimal" or "decimal". This is just an imprecise spelling that is used because of laziness. Numbers are represented decimal or hexadecimal would be precise. There's no need to convert an int
from decimal to hexadecimal. In fact they're stored in binary-format, no matter what notation you use in the code. The only point where notation is relevant is for user-interactions or during coding, like in- and outputting numbers, or specifying constants in the code.
Upvotes: 0