Printing binary values in Java - java

Why the output of this java program is 8 and 9 while we try to print 010 and 011 respectively:
public class Test{
public static void main(String str[]){
System.out.println(011);
}
}
What is the reason?

In Java, the default conversion from integer to string is base 10. If you want a different radix, you have to specify it explicitly. For instance, you can convert an integer value to a binary string using:
Integer.toString(value, 2);
Similarly, you can convert it to an octal value with:
Integer.toString(value, 8);
Unless the value is 0, the string will not have a leading zero. If you want a leading 0, you'll have to prepend it. Alternatively, you can format it with String.format() and specify zero fill and a minimum width for the converted string:
String.format("%1$03o", value); // the "1$ in the format string is optional here
P.S. It's not clear from your question what the exact problem is. It sounds like it's that you are converting from an integer value to a string. However, if the problem is that you're trying to read the string "011" and it is being read as the integer value 9, this is because a leading 0 forces interpretation as an octal value. You'll have to read it as a String value and then explicitly specify the conversion from string to integer to be base 10:
int val = Integer.valueOf(stringValue, 10);

010 is interpretetion of 10 in octal base which is 8. And similarly 011 is interpretetion of 11 in octal base which is 9.
Prepending an integer with 0 makes it interpreted in octal base.
Similarly, you can try printing 0x10, which is a hexadecimal representation, and will give you 16 as output.

- If you want to convert the integer to binary data, use toBinaryString() method.
Eg:
int i = 8;
Integer.toBinaryString(i);

bec. when you start your number with 0 JVM convert the number from decimal to octal that's all ;)
"11 in decimal = 9 in octal"
decimal 0 1 2 3 4 5 6 7 8 9
octal 0 1 2 3 4 5 6 7 10 11

Related

IOStream writing data to console

I have read that only lower order 8 bits are used while Output of byte output stream, then why I am getting 5?
Also, why I am not getting the binary or hex format of 65?
If I delete the leading 2 zeros and make the value of b as 65 then I get 'A' as the answer but why by placing leading 2 zeros I am not getting the answer but '5'?
Also why I am getting the answer as a character and not in binary format as 'out' is a Byte OutputStream object and should write in bytes?
public static void main(String[] args) {
int b = 0065;
System.out.write(b);
System.out.flush();
}
desired 'A', actual 5?
Also, desired 0100 0001.
Static field out in class java.lang.System has type java.io.PrintStream.
Class PrintStream has several write() methods. In your code, the argument you are passing to method write() is an int, hence the method invokde is write(int). You are assigning a number literal to your local variable b. In java, a number literal that begins with a zero (0) indicates an octal number and 65 in octal is 53 (fifty-three) in decimal and 53 is the ASCII code for the digit 5 (five). For your information, class java.lang.Integer has static method toBinaryString(). I suggest you look at the javadoc for that method.
public class StackOverFlow{
public static void main(String []args){
int x = 0065;// in java when you append zero like 011 or 0023 its take as octal number,when you print it will convert to decimal
System.out.println(x); // 0065 is octal value when you convert to decimal it will be 53 and in hexa 35
int y = 056;//octal value
System.out.println(y); // Output:46 decimal value
}
}
Because 0065 is octal for decimal 53 for hexadecimal 0x35 for the ASCII character 5.

"The literal 0008 of type int is out of range" [duplicate]

I am trying to write following code.but it gives me error kindly help me.
int six=06;
int seven=07;
int abc=018;
int nine=011;
System.out.println("Octal 011 ="+nine);
System.out.println("octal O18 =" + abc);
why i cant give 018 and 019 to variable.i can give value 020 and 021 to variable.
Why this happen? what's the reason behind this Kindly tell me.
I got Following error
integer number too large: 018
int eight=018;
Octal is base-8 number system, so it means digit can be from 0 to 7, you can't use digit 8 (and 9 too) in octal number system.
// Decimal declaration and possible chars are [0-9]
int decimal = 495;
// HexaDecimal declaration starts with 0X or 0x and possible chars are [0-9A-Fa-f]
int hexa = 0X1EF;
// Octal declaration starts with 0 and possible chars are [0-7]
int octal = 0757;
// Binary representation starts with 0B or 0b and possible chars are [0-1]
int binary = 0b111101111;
If the number is string format then you can convert it into int using the below
String text = "0b111101111";
int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
why i cant give 018 and 019 to variable.
Because an integer literal prefixed with 0 is treated as octal, and '8' and '9' aren't valid octal digits.
From section 3.10.1 of the JLS:
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
Trying to use '8' in an octal number is like trying to use 'G' in hex... it's simple not part of the set of symbols used in that base.
Octal numbers (base 8) can only use the following figures: 01234567. The same way that decimal numbers (base 10) can only use 0123456789.
So in octal representation, 17 + 1 is 20.
The prefix 0 indicates octal(8 base)(digits 0-7).
public class MainClass{
public static void main(String[] argv){
int intValue = 034; // 28 in decimal
int six = 06; // Equal to decimal 6
int seven = 07; // Equal to decimal 7
int eight = 010; // Equal to decimal 8
int nine = 011; // Equal to decimal 9
System.out.println("Octal 010 = " + eight);
}
}
why i cant give 018 and 019 to variable.i can give value 020 and 021 to variable.
The leading zero signifies an octal literal. However, 8 and 9 are not valid octal digits. This makes 018 and 019 invalid.
When an integer literal starts with 0 in Java, it's assumed to be in octal notation. The digits 8 and 9 are illegal in octal—the digits can range only between 0 and 7.
Because it's octal, an octal number has 8 digits which spans from 0 to 7 inclusive. For the same reason 12 would be an invalid binary number.
You need at least base 9 to have 18 and a normal decimal base for 19.
For your query.....you assign an invalid value to the variable....your assigned value is started with 0(zero) ..which means that you are assigning an octal value to the variable and when you assign a value higher then 7 such as 018 in your case...the value excedes the range of octal variables and hence show an error...so try entering simply 18 so it would take it as an integer rather than an octal variable data type...

Java convert 16 bits signed to 4 digits hex

When dealing with signed int conversion to hex, only Integer.toString(value, 16) is useful
see a post on subject
but I need to format with 4 hex digits (leading zeros for positive numbers and not 32bits/8chars for negatif numbers),
in C++ the right function is IntToHex( value,4)
http://docwiki.embarcadero.com/Libraries/XE3/en/System.SysUtils.IntToHex
But I didn't fiund the equivalent in Java (Android).
Found it :
int StepRef =-2;
String SS = String.format("%08X",StepRef);
String SS4 = SS.substring(SS.length() - 4);

Unexpected int/Integer behavior when number starts by 0

I can't understand why this is not printing the expected value (400300) when I put extra zeros in front of the number:
System.out.println(new Integer(0400300)); // prints 131264
System.out.println(0400300); // prints 131264
If I put one or more zeros in front of the number, the expected value is not printed.
// JUnit test does not pass:
assertTrue(0400300 == 400300); // returns false!?
Adding 0 to the front made the number an Octal literal. So:
0400300 = 3 * 8 ^ 2 + 4 * 8 ^ 5 = 131264
See JLS for the relevant sections. Quote:
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

How do I convert a decimal fraction to binary in Java?

I need to convert 0.5 in base 10 to base 2 (0.1).
I have tried using
Double.doubleToRawLongBits(0.5)
and it returns 4602678819172646912 which I guess is in hex, but it does not make sense to me.
No. 4602678819172646912 is in dec, hex is 0x3fe0000000000000. To dismantle that:
3 | F | E | 0 ...
0 0 1 1 1 1 1 1 1 1 1 0 0 ...
s| exponent | mantissa
s is the sign bit, exponent is the exponent shifted by 2^9 (hence this exponent means -1), mantissa is the xxx part of the number 1.xxx (1. is implied). Therefore, this number is 1.000...*2^-1, which is 0.5.
Note that this describes the "normal" numbers only, so no zeros, denormals, NaNs or infinities
Multiply you number by 2^n, convert to an BigInteger, convert to binary String, add a decimal point at position n (from right to left).
Example (quick & ++dirty):
private static String convert(double number) {
int n = 10; // constant?
BigDecimal bd = new BigDecimal(number);
BigDecimal mult = new BigDecimal(2).pow(n);
bd = bd.multiply(mult);
BigInteger bi = bd.toBigInteger();
StringBuilder str = new StringBuilder(bi.toString(2));
while (str.length() < n+1) { // +1 for leading zero
str.insert(0, "0");
}
str.insert(str.length()-n, ".");
return str.toString();
}
This is decimal for 0x3FE0_0000_0000_0000. The mantissa is the list of zeros after 3FE (which codes sign and exponent). This is what you are looking for, given that 0.1 before the zeros is implicit.
Do you want to convert the decimal string to floating-point binary or to a binary string? If the former, just use valueOf(); if the latter, use valueOf() followed by toString() or printf().
0.1 is NOT a binary representation of 0.5
Java will represent 0.5 using IEEE 754, as specified on the Java Language Specification. BigInteger.valueOf(Double.doubleToRawLongBits(0.5)).toByteArray() will give you a byte per byte representation of 0.5 as Java does internally.

Categories

Resources