Integer.valueOf() static function - java

Integer b = Integer.valueOf("444",8);
System.out.println(b);
why b=292 I can't understand this static function
and when
b=Integer.valueOf("444",16);
System.out.println(b)
why b=1092
I appreciate your help
Thanks in advance

As usual sigh the docs are there to read them. http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf%28java.lang.String,%20int%29
Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument.
This means, if you pass 16 as second argument, the number will be interpreted as a hexadecimal number, thus: 4 * 16 ^ 2 + 4 * 16 + 4 = 1092. Same for octal, only with radix 8.

You are providing the radix as octal and hexa so you are getting the output as per the radix provided:
static Integer valueOf(String s, int radix)
As per the java documentation Integer.valueOf:
Returns an Integer object holding the value extracted from the
specified String when parsed with the radix given by the second
argument. The first argument is interpreted as representing a signed
integer in the radix specified by the second argument, exactly as if
the arguments were given to the parseInt(java.lang.String, int)
method. The result is an Integer object that represents the integer
value specified by the string.

Because 444 in base 8 = 292 in base 10 and 444 in base 16 = 1092 in base 10.

"444" is the string and 16 is called as the radix, one thing to be noted is that decimal is the default base.
Now the radix is the present base of the argument in this case its 16 i.e. hex which needs to be converted to default i.e. decimal so
444(hex) to decimal is 1092.

Related

Error parsing 16 bit short

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive)
Why does the following
System.out.println(Short.parseShort("1111111111111111", 2));
Return
java.lang.NumberFormatException: Value out of range.
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.
The value represented by the string is not a value of type short.
I assume the error is from the last bullet, but
I thought 16 '1' bits is equivalent to -1 when using Short. Thus, it should be valid?
1111111111111111 should be converted to 65535, which is greater than the maximum value(32,767) short can represent. Try some smaller numbers.
The javadoc that you quoted states that Short.parseShort parses numbers as signed numbers.
1111111111111111 (16 1 digits) when read as a signed number means 216 - 1 or 65535. That is too large to be represented as a short.
Alternatives:
If there was an alternative to parseShort that parsed unsigned values, that would work. (But there isn't ...)
You could use Integer.parseInt, do a range check on the int result, and then cast it to a short.
I thought 16 '1' bits is equivalent to -1 when using Short. Thus, it should be valid?
Unfortunately, no. The parseInt method parses signed values.
Thought experiment: what if the user entered 1111111111111111 with the intention that it really meant a positive signed number; i.e. +65535? How would that mesh with your idea that the parse method treats signed and unsigned as interchangeable?

Output of System.out.println(-1) will be Integer or String?

When we write:
System.out.println(-1);
Does Java consider -1 as Integer or String?
If you follow the documentation, you find:
public void println(int x)
Prints an integer and then terminate the line. This method behaves as though it invokes print(int) and then println().
Then the print(int) documentation says:
The string produced by String.valueOf(int) is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
So it converts the integer to a String before converting that to bytes and printing it out.
Does Java consider -1 as Integer or String?
Neither. -1 is a primitive int literal.
Why is -1 a primitive int literal?
int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1.
Also:
Integer literals can be expressed by these number systems:
Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day
Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F
Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later)
See Primitive Data Types
Take a look at the official documentation: System.out.println can accept a lot of parameters, and since you're passing -1 and this has int type, then the method called in your case is public void println(int x).
Behind the scenes though, the -1 is converted into String then into the bytes representation, according to your platform's default character encoding before being sent to the console.
Actually, to be technical- it is neither. Integer is specific to an Integer object in java (As in ArrayList<Integer>) An Integer object is not the same as an int. Your print statement considers the argument as an int.
ArrayList<Integer> integers = new ArrayList<Integer> ();
integers.add(FooIntegerObject);
System.out.print(-1); //is an int
System.out.print("-1"); //is a String
System.out.print(integers(0).toString()); //is an Integer

assign hex value for short data type

I know that assigning 0x9d for short data type will work. but when i'm print it out, it displays 157. it should retain as 0x9d because im planning to pass that data to a library which accepts short data type only and should be 0x9d for example.
here's the portion of my code where i got the error.
short module_id = (short) 0x9d; // defined in system.txt
System.out.print("hello: " + String.format("%x", module_id));
roamerLocator.receiveMsg(module_id);
}
protected void receiveMsg(short moduleId) {
try {
System.out.println("\ninside: " + moduleId);
GctMsg gctMsg = GctLib.receive(moduleId);
this is for my ss7 configuration . the defined parameters in ss7 configuration should be accepting 0x9d instead of decimal which is 157. and the "GctMsg gctMsg = GctLib.receive(moduleId);" accepts only short data type
I think you're misunderstanding what hexadecimal and decimal are meant to represent.
Decimal is a numerical representation in base 10 - you know, counting from 0 to 9. That's the system we're used to.
Hexadecimal is a numerical representation in base 16 - which goes from 0 to F.
In effect, your concern is that 157 isn't the same as 0x9D, when it actually is.
Hexadecimal is more a formal representation, and it doesn't change the underlying value of the number. So, you should be okay to see 157 passed in to your method.
If you really want to see it again as 0x9d, you can use String#format inside of your System.out.println:
System.out.println("\ninside: " + String.format("%x", moduleId));

Bitwise negation gives unexpected result

I am trying to write a bitwise calculator in java, something that you could input an expression such as ~101 and it would give back 10 however when i run this code
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Integer a = Integer.valueOf("101", 2);
System.out.println(Integer.toString(~a,2));
}
}
it outputs -110 why?
You are assuming that 101 is three bits long. Java doesn't support variable length bit operations, it operates on a whole int of bits, so ~ will be the not of a 32 bit long "101".
--- Edited after being asked "How can I fix this?" ---
That's a really good question, but the answer is a mix of "you can't" and "you can achieve the same thing by different means".
You can't fix the ~ operator, as it does what it does. It would sort of be like asking to fix + to only add the 1's place. Just not going to happen.
You can achieve the desired operation, but you need a bit more "stuff" to get it going. First you must have something (another int) that specifies the bits of interest. This is typically called a bit mask.
int mask = 0x00000007; // just the last 3 bits.
int masked_inverse = (~value) & mask;
Note that what we did was really invert 32 bits, then zeroed out 29 of those bits; because, they were set to zero in the mask, which means "we don't care about them". This can also be imagined as leveraging the & operator such that we say "if set and we care about it, set it".
Now you will still have 32 bits, but only the lower 3 will be inverted. If you want a 3 bit data structure, then that's a different story. Java (and most languages) just don't support such things directly. So, you might be tempted to add another type to Java to support that. Java adds types via a class mechanism, but the built-in types are not changeable. This means you could write a class to represent a 3 bit data structure, but it will have to handle ints internally as 32 bit fields.
Fortunately for you, someone has already done this. It is part of the standard Java library, and is called a BitSet.
BitSet threeBits = new BitSet(3);
threeBits.set(2); // set bit index 2
threeBits.set(0); // set bit index 0
threeBits.flip(0,3);
However, such bit manipulations have a different feel to them due to the constraints of the Class / Object system in Java, which follows from defining classes as the only way to add new types in Java.
If a = ...0000101 (bin) = 5 (dec)
~a = ~...0000101(bin) = ...1111010(bin)
and Java uses "Two's complement" form to represent negative numbers so
~a = -6 (dec)
Now difference between Integer.toBinaryString(number) and Integer.toString(number, 2) for negative number is that
toBinaryString returns String in "Two's complement" form but
toString(number, 2) calculates binary form as if number was positive and add "minus" mark if argument was negative.
So toString(number, 2) for ~a = -6 will
calculate binary value for 6 -> 0000110,
trim leading zeros -> 110,
add minus mark -> -110.
101 in integer is actually represented as 00000000000000000000000000000101 negate this and you get 11111111111111111111111111111010 - this is -6.
The toString() method interprets its argument as a signed value.
To demonstrate binary operations its better to use Integer.toBinaryString(). It interprets its argument as unsigned, so that ~101 is output as 11111111111111111111111111111010.
If you want fewer bits of output you can mask the result with &.
Just to elaborate on Edwin's answer a bit - if you're looking to create a variable length mask to develop the bits of interest, you might want some helper functions:
/**
* Negate a number, specifying the bits of interest.
*
* Negating 52 with an interest of 6 would result in 11 (from 110100 to 001011).
* Negating 0 with an interest of 32 would result in -1 (equivalent to ~0).
*
* #param number the number to negate.
* #param bitsOfInterest the bits we're interested in limiting ourself to (32 maximum).
* #return the negated number.
*/
public int negate(int number, int bitsOfInterest) {
int negated = ~number;
int mask = ~0 >>> (32 - bitsOfInterest);
logger.info("Mask for negation is [" + Integer.toBinaryString(mask) + "]");
return negated & mask;
}
/**
* Negate a number, assuming we're interesting in negation of all 31 bits (exluding the sign).
*
* Negating 32 in this case would result in ({#link Integer#MAX_VALUE} - 32).
*
* #param number the number to negate.
* #return the negated number.
*/
public int negate(int number) {
return negate(number, 31);
}

Wrapper's parseXXX() for signed binary misunderstanding

Let's take Byte.parseByte() as an example as one of the wrappers' parseXXX().
From parseByte(String s, int radix)'s JavaDoc:
Parses the string argument as a signed byte in the radix specified by
the second argument.
But that's not quite true if radix = 2. In other words, the binary literal of -127 is 10000000:
byte b = (byte) 0b10000000;
So the following should be true:
byte b = Byte.parseByte("10000000", 2);
but unfortunately, it throws NumberFormatException, and instead I have to do it as follows:
byte b = Byte.parseByte("-111111", 2);
where parseByte() parses the binary string as a sign-magnitude (the sign and the magnitude), where it should parse as a signed binary (2's complement, i.e. MSB is the sign-bit).
Am I wrong about this?
Am I wrong about this?
Yes. The Javadoc says nothing about 2's-complement. Indeed, it explicitly states how it recognises negative values (i.e. a - prefix, so effectively "human-readable" sign-magnitude).
Think about it another way. If parseByte interpreted radix-2 as 2's-complement, what would you want it to do for radix-10 (or indeed, any other radix)? For consistency, it would have to be 10's-complement, which would be inconvenient, I can assure you!
This is because for parseByte "10000000" is a positive value (128) which does not fit into byte values range -128 to 128. But we can parse two's comlement binary string representation with BigInteger:
byte b = new BigInteger("10000000", 2).byteValue()
this gives expected -128 result

Categories