I was playing a bit with numbers, and something interesting came upon me, which I don't quite understand.
public static void main(String[] args) {
int hexNumber = 0x7A;//decimal: 122 binary:0111 1010
int decNumber = 122;
int binNumber = 1111010;
System.out.println(hexNumber);//122
System.out.println(Integer.toString(hexNumber, 16)); //7a
System.out.println(Integer.toHexString(hexNumber)); //7a
System.out.println(Integer.toString(hexNumber, 2)); // 1111010
System.out.println(Integer.toBinaryString(hexNumber)); //1111010
System.out.println(hexNumber==binNumber);//false
System.out.println(hexNumber==decNumber);//true
System.out.println(decNumber==binNumber);//false
}
Why do I get "false" at #1 and #3? Doesn't change even if binNumber = 01111010;
Well, you can't directly store binary values in Java without any prefix.
binNumber isn't stored as the binary number 1111010; instead, it's stored as the decimal number 1111010.
This you have to store as int binNumber = Integer.parseInt("1111010", 2); or better yet int binNumber = 0b1111010;.
For octal:
int octalNo = 0177; //'0' is prefix
or
int octalNo = Integer.parseInt("0177", 8); //leading '0's are ignored
For hexadecimal:
int hexNo = 0x177; //'0x' is prefix
or
int hexNo = Integer.parseInt("0177", 16); //leading '0's are ignored
For more info, have a look at this.
You aren't creating the binary number as a binary one. You are creating it as a decimal one (base 10) that happens to only contain 0s and 1s.
To store 0111 1010 in Java 7 use the new binary literal (you can even use underscores for easier reading)
int binNumber = 0b0111_1010;
Because that's not the proper way to specify the binary number (and there is no such way in Java, apart from something like Integer.toBinaryString(122) which would give you a proper binary representation (returned as a String)).
Your number was interpreted as a "normal" decimal integer (if entered without leading 0) or as an integer in octal system (if entered with leading 0).
In Java versions before 7, you need to use this
int binNumber = Integer.parseInt("1111010", 2);
In 7 and up, you can use
int binNumber = 0b1111010;
With that change, your code works here (I get three true resuls).
The answer is clear. You have assigned to integers some diferent values.hexNumber is initialized to decimal value 122, even if the representation you use for that is hexadecimal. decNumber is initialized to decimal value 122, so when you compare hexNumber and decNumber you will get true because it's really the same value. Finally binNumber is initialized to the decimal value 1111010, so if you compare it with one of the other numbers you will get false.
Related
PS: I tried searching many existing questions here on Stackoverflow, however it
only added chaos to my query!
10101
11100
11010
00101
Consider this as a sample Input, which I need to read as BinaryString one by one! Then I need to represent them as an Integer.
Obviously int x = 20 initializes x as a decimal Integer,
and I read from other questions that int y = 0b101 initializes y as a binary Integer.
Now, The question is: If I have a binaryString, how do I cast it into an int like with a preceding 0b . My objectives following this is to perform bit level OR and XOR operations.
ie from the above input, I need to do 10101 ^ 11100
Let me know if this is the right way to approach a problem like this, Thanks!
If I have understood your question correctly, you want to know how to represent Binary Strings as Integer.
Well, you can perform this task for conversion of Binary String to Integer:
String input = "0b1001";
String temp = input.substring(2);
int foo = Integer.parseInt(temp, 2);
Alternately, to switch back :
String temp = Integer.toBinaryString(foo);
from the above input, I need to do 10101 ^ 11100.
You can achieve the same using proper decimal representation of integer. If you want to re-invent the wheel, then
first convert the decimal representation of the given number to Binary String(using step 2);
then convert to integer value using step 1;
repeat steps 1 and 2 for the second number; and
finally, perform the XOR operation over them.
But, I don't see how it'll be performing/calculating differently. It'd still be stored as the same integer. It is just that you will get extra satisfaction(on your part) that the number was read as an integer and then converted to Binary representation of that number.
Try Integer.parseInt(String s, int radix). It will throw an exception if the binary string is invalid, so you might want to validate the input.
String binary = "10001";
int asInt = Integer.parseInt(binary, 2); // 17
int supports ^ (bitwise XOR) operator. All you have to do is convert your binary strings to int variables and perform the desired operations.
I want to display the length of a 4-digit number displayed by the user, the problem that I'm running into is that whenever I read the length of a number that is 4-digits long but has trailing zeros the length comes to the number of digits minus the zeros.
Here is what I tried:
//length of values from number input
int number = 0123;
int length = (int)Math.log10(number) + 1;
This returns to length of 3
The other thing I tried was:
int number = 0123;
int length = String.valueOf(number).length();
This also returned a length of 3.
Are there any alternatives to how I can obtain this length?
Because int number = 0123 is the equivalent of int number = 83 as 0123 is an octal constant. Thanks to #DavidConrad and #DrewKennedy for the octal precision.
Instead declare it as a String if you want to keep the leading 0
String number = "0123";
int length = number.length();
And then when you need the number, simply do Integer.parseInt(number)
Why is the syntax of octal notation in java 0xx ?
Java syntax was designed to be close to that of C, see eg page 20 at
How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008
by James Gosling (20_Gosling_keynote.pdf):
In turn, this is the way how octal constants are defined in C language:
If an integer constant begins with 0x or 0X, it is hexadecimal. If it
begins with the digit 0, it is octal. Otherwise, it is assumed to be
decimal...
Note that this part is a C&P of #gnat answer on programmers.stackexchange.
https://softwareengineering.stackexchange.com/questions/221797/reasoning-behind-the-syntax-of-octal-notation-in-java
Use a string instead:
String number = "0123";
int length = number.length(); // equals 4
This doesn't work with an int, as the internal representation of 0123 is identical to 123. The program doesn't remember how the value was written, only the actual value.
What you can do is declare a string:
String number = "0123";
int numberLengthWithLeadingZeroes = number.length(); // == 4
int numberValue = Integer.parseInt(number); // == 123
If you really want to include leading 0's you could always store it in an array of of characters
example:
char[] abc = String.valueOf(number).toCharArray();
Then obviously you can figure out the length of the array.
As several people have pointed out already though, integers don't have leading 0's.
String abc=String.format("%04d", yournumber);
for zero-padding with length=4.
Refer to this link .
http://download.oracle.com/javase/7/docs/api/java/util/Formatter.html
this might help u ..
Integers in Java don't have leading zeroes. If you assign the value 0123 to your int or Integer variable, it will be interpreted as an octal constant rather than a decimal one, which can lead to subtle bugs.
Instead, if you want to keep leading zeroes, use a String, e.g.
String number = "0123";
This way you can also measure the length:
String number = "0123";
System.out.println(number.length());
I can't think of a better way to left pad an integer with zeroes without first converting it to a String. Is there a way to do this? I've found numerous questions regarding this but they all require a String conversion. I understand we can find the length with this approach:
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
However, this will still require me to convert it to a String and back afterwards. Surely, there's a better way?
No. An int represents a mathematical integer value, represented as 32 bits. The number 0001 is 1, and has a unique binary representation. Left-padded integers are not integers. they are Strings.
No. Numeric types cannot contain leading zeros. This a feature of the formatted textual representation i.e. Strings
Since you already have the length I'm guessing the leading zero's are simply for output, but ultimately your question was answered by the other two posters.
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
String zeros;
for(int i=0; i<length; i++) {
zeros = zeros.concat("0");
}
System.out.println(zeros + num);
How can I convert an int number from decimal to binary. For example:
int x=10; // radix 10
How can I make another integer has the binary representation of x, such as:
int y=1010; // radix 2
by using c only?
An integer is always stored in binary format internally -- saying that you want to convert int x = 10 base 10 to int y = 1010 base 2 doesn't make sense. Perhaps you want to convert it to a string representing the binary format of the integer, in which case you can use Integer.toBinaryString.
First thing you should understand is that a value is an abstract notion, that is not bounded to any representation. For example, if you have 20 apples, the number of apples will be the same regardless of the representation. So, dec("10") == bin("1010").
The value of an int reffers to this abstract notion of value, and it does not have any form until you with to print it. This means that the notion of base is important only for conversions from string to int and back.
String s = Integer.toBinaryString(10);
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html
Whether it's binary or decimal doesn't really have anything to do with the integer itself. Binary or decimal is a property of a physical representation of the integer, i.e. a String. Thus, the methods you should look at are Integer.toString() and Integer.valueOf() (the versions that take a radix parameter).
BTW, internally, all Java integers are binary, but literals in the source code are decimal (or octal).
Your question is a bit unclear but I'll do my best to try to make sense of it.
How can I make another integer has the binary representation of x such as: int y=1010 radix 2?
From this it looks like you wish to write a binary literal in your source code. Java doesn't support binary integer literals. It only supports decimal, hexadecimal and octal.
You can write your number as a string instead and use Integer.parseInt with the desired radix:
int y = Integer.parseInt("1010", 2);
But you should note that the final result is identical to writing int y = 10;. The integer 10 that was written as a decimal literal in the source code is identical in every way to one which was parsed from the binary string "1010". There is no difference in their internal representation if they are both stored as int.
If you want to convert an existing integer to its binary representation as a string then you can use Integer.toBinaryString as others have already pointed out.
Both integers will have the same interior representation, you can however display as binary via Integer.toBinaryString(i)
Use Integer.toBinaryString()
String y = Integer.toBinaryString(10);
Converting an integer to another base (string representation):
int num = 15;
String fifteen = Integer.toString(num, 2);
// fifteen = "1111"
Converting the string back into an integer
String fifteen = "1111";
int num = Integer.valueOf(fifteen, 2);
// num = 15
This covers the general case for any base. There's no way to explicitly assign an integer as binary (only decimal, octal, and hexadecimal)
int x = 255; // decimal
int y = 0377; // octal (leading zero)
int z = 0xFF; // hex (prepend 0x)
I am getting a number format exception when trying to do it
int temp = Integer.parseInt("C050005C",16);
if I reduce one of the digits in the hex number it converts but not otherwise. why and how to solve this problem?
This would cause an integer overflow, as integers are always signed in Java. From the documentation of that method (emphasis mine):
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') provided that the string is longer than length 1.
The value represented by the string is not a value of type int.
It would fit into an unsigned integer, though. As of Java 8 there's Integer.parseUnsignedInt (thanks, Andreas):
int temp = Integer.parseIntUnsigned("C050005C",16);
On earlier Java versions your best bet here might to use a long and then just put the lower 4 bytes of that long into an int:
long x = Long.parseLong("C050005C", 16);
int y = (int) (x & 0xffffffff);
Maybe you can even drop the bitwise "and" here, but I can't test right now. But that could shorten it to
int y = (int) Long.parseLong("C050005C", 16);
C050005C is 3226468444 decimal, which is more than Integer.MAX_VALUE. It won't fit in int.
Use this:
long temp = Long.parseLong("C050005C",16);
The signed int type ranges from 0x7FFFFFFF to -0x80000000.