I know I could use String.substring or write some extra code, but is there a simple way to achieve this by only using String.format?
For example, I only want the first 6 chars "1234ab" in the result:
int v = 0x1234abcd;
String s = String.format("%06x", v) // gives me 1234abcd
String s = String.format("%06.6x", v) // gives me IllegalformatPrecesionException
The Java Formatter doc said the precision could be used to limit the overall output width, but only to certain data types.
Any ideas? Thanks.
Depending how may hex digits you want to truncate...
You can divide by powers of 16
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
// This will truncate the 2 right most hex digits
String hexV = Integer.toHexString(v / (int)Math.pow(16, 2));
System.out.println(hexV);
}
Results:
1234ab
Even if you mess up and divide by a power of 16 that exceeds the length of your hex string, the result will just be zero.
Then there's the substring() approach
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
String hexV = Integer.toHexString(v);
// This will truncate the the 2 most right hex digits
// provided the length is greater than 2
System.out.println(hexV.length() > 2 ? hexV.substring(0, hexV.length() - 2) : hexV);
}
Since you wanted to do this with just the Formatter.
Here's my result.
1234ab
1234abcd
And here's the code.
public class Tester {
public static void main(String[] args) {
int v = 0x1234abcd;
String s = String.format("%6.6s", String.format("%x", v));
System.out.println(s);
s = String.format("%10.10s", String.format("%x", v));
System.out.println(s);
}
}
I convert the hex number to a String, then truncate or left pad the String with the second Formatter.
Related
This question already has answers here:
Java Integer parseInt error
(4 answers)
Closed 6 years ago.
I need to convert the string of hex to decimal in java..
My hex value is "00000156A56BE980".
My required output is 1471654128000
I have done the following in java,
public static void main (String args [])
{
String hexValue = " 00000156A56BE980 ";
Integer result = Integer.parseInt(hexValue, 16);
System.out.println(result);
}
but I am getting the following error,
Number format Exception for input string "00000156A56BE980"
I have tried by giving long also the same error coming.. For other hex value it's coming but when we give hex string of larger value it shows the error.
How can we convert this number to decimal?
Can anyone solve this issue for me?
Try it like so
import java.math.*;
class Main {
public static void main (String args [])
{
String hexValue = "00000156A56BE980";
BigInteger result = new BigInteger(hexValue, 16);
System.out.println(result);
}
}
See also this repl.it
The problem is probably because your value does not fit within the value range (-231 to 232-1) of Integer - see the docs
The number is too large for a 32-bit int
Try using a long instead.
public static void main(String[] args) {
String hexValue = "00000156A56BE980";
long result = Long.parseLong(hexValue, 16);
System.out.println(result);
}
Note: you can't have spaces in a number. You can call .trim() to remove them.
2 thing in order the code can work:
remove spaces trimming the String
the result doenst fit in an integer so use either Long or BigInteger instead
public static void main(String[] args) {
String hexValue = " 00000156A56BE980 ";
long result = Long.parseLong(hexValue.trim(), 16);
System.out.println(result);
}
The number is too big for integer (> 2^32).
(The value represented by the string is not a value of type int.)
Take a look here
Below is a snippet of my java code.
//converts a binary string to hexadecimal
public static String binaryToHex (String binaryNumber)
{
BigInteger temp = new BigInteger(binaryNumber, 2);
return temp.toString(16).toUpperCase();
}
If I input "0000 1001 0101 0111" (without the spaces) as my String binaryNumber, the return value is 957. But ideally what I want is 0957 instead of just 957. How do I make sure to pad with zeroes if hex number is not 4 digits?
Thanks.
You do one of the following:
Manually pad with zeroes
Use String.format()
Manually pad with zeroes
Since you want extra leading zeroes when shorter than 4 digits, use this:
BigInteger temp = new BigInteger(binaryNumber, 2);
String hex = temp.toString(16).toUpperCase();
if (hex.length() < 4)
hex = "000".substring(hex.length() - 1) + hex;
return hex;
Use String.format()
BigInteger temp = new BigInteger(binaryNumber, 2);
return String.format("%04X", temp);
Note, if you're only expecting the value to be 4 hex digits long, then a regular int can hold the value. No need to use BigInteger.
In Java 8, do it by parsing the binary input as an unsigned number:
int temp = Integer.parseUnsignedInt(binaryNumber, 2);
return String.format("%04X", temp);
The BigInteger becomes an internal machine representation of whatever value you passed in as a String in binary format. Therefore, the machine does not know how many leading zeros you would like in the output format. Unfortunately, the method toString in BigInteger does not allow any kind of formatting, so you would have to do it manually if you attempt to use the code you showed.
I customized your code a bit to include leading zeros based on input string:
public static void main(String[] args) {
System.out.println(binaryToHex("0000100101010111"));
}
public static String binaryToHex(String binaryNumber) {
BigInteger temp = new BigInteger(binaryNumber, 2);
String hexStr = temp.toString(16).toUpperCase();
int b16inLen = binaryNumber.length()/4;
int b16outLen = hexStr.length();
int b16padding = b16inLen - b16outLen;
for (int i=0; i<b16padding; i++) {
hexStr=('0'+hexStr);
}
return hexStr;
}
Notice that the above solution counts up the base16 digits in the input and calculates the difference with the base16 digits in the output. So, it requires the user to input a full '0000' to be counted up. That is '000 1111' will be displayed as 'F' while '0000 1111' as '0F'.
I would like to format byte as a two character hex number. In C# you would do this:
string.Format("{0:X2}", recvBuff[indx])
How do you do the same thing in Java?
The toString-method of Integer and Long can take a base, up to 36 afaik, so you would pick 16:
String hex = Integer.toString (recvBuff[indx], 16);
Since your question asks for a "two character", you will have to make sure values are not greater than 256 (otherwise will print 3 hex digits or more). You also need to pad with zero if values less than 16.
public class HexTwoChars
{
static public void main(String[] args)
{
int values[] = { 1, 100, 10000 };
for (int v: values)
System.out.println( String.format("%02x", v % 256 ));
}
}
Running this program prints
01
64
10
class Test{
public static void main(String Args[]){
Integer x;
x = Integer.decode("0b111");
System.out.println(x);
}
}
This doesn't work with the prefix 0 for binary and for octal with the prefix 0.
What is the correct way to do it?
Looking at the documentation for Integer.decode, I see no indication that binary should work. Octal should work though, with a prefix of just 0:
System.out.println(Integer.decode("010")); // Prints 8
You could handle a binary indicator of "0b" like this:
int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
Complete sample code showing binary, octal, decimal and hex representations of 15:
public class Test {
public static void main(String[] args) throws Exception {
String[] strings = { "0b1111", "017", "15", "0xf" };
for (String string : strings) {
System.out.println(decode(string)); // 15 every time
}
}
private static int decode(String text) {
return text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
}
}
Integer.decode cannot parse binary, see API. But octal work fine, example:
int i = Integer.decode("011");
As of Java 7, you can use binary literals directly in your code. However, note that these are of type byte, short, int or long (and not String).
int x = 0b111;
how can we convert hexadecimal number string to double-precision number in java ?
in matlab it's simple :
>> hex2num('c0399999a0000000')
ans =
-25.6000
but could I do the same things in java also ?
I tried parseInt() but this number is not integer.
I think you want Double.longBitsToDouble, like this:
public class Test {
public static void main(String[] args) {
String hex = "c0399999a0000000";
long longHex = parseUnsignedHex(hex);
double d = Double.longBitsToDouble(longHex);
System.out.println(d);
}
public static long parseUnsignedHex(String text) {
if (text.length() == 16) {
return (parseUnsignedHex(text.substring(0, 1)) << 60)
| parseUnsignedHex(text.substring(1));
}
return Long.parseLong(text, 16);
}
}
(The fact that long is signed in Java makes this more awkward than you'd really want, but hey...)
First make a long, and then call longBitsToDouble