I am following the below method
new Biginteger(str,16).toString(2);
It works really well, but it removes leading zeros. I need output in 64 bits if input string is "3031323334353637"
But it returns 62 characters. I can use a for loop to do that. Is there any other way to do that without loop?
Goal: Converting hex to binary with leading zeros
You can pad with spaces using String.format("%64s") and then replace spaces with zeros. This has the advantage of working for any size of input, not just something in the int range. I'm guessing you're working with arbitrary inputs from your use of BigInteger...
String value = new BigInteger("3031323334353637", 16).toString(2);
System.out.println(String.format("%64s", value).replace(" ", "0"));
Output
0011000000110001001100100011001100110100001101010011011000110111
Explanation... The String.format("%64s, value) outputs the earlier String padded to fill 64 characters.
" 11000000110001001100100011001100110100001101010011011000110111"
The leading spaces are then replaced with '0' characters using String.replace(oldString, newString)
"0011000000110001001100100011001100110100001101010011011000110111"
The following may be the easiest:
new BigInteger("1" + str,16).toString(2).substring(1)
Check out this question.
You can do it using String.format():
String unpaddedBinary = new BigInteger("a12", 16).toString(2);
String paddedBinary = String.format("%064s", Integer.parseInt(unpaddedBinary, 2));
Related
I need to create a summary table at the end of a log with some values that
are obtained inside a class. The table needs to be printed in fixed-width
format. I have the code to do this already, but I need to limit Strings,
doubles and ints to a fixed-width size that is hard-coded in the code.
So, suppose I want to print a fixed-width table with
int,string,double,string
int,string,double,string
int,string,double,string
int,string,double,string
and the fixed widths are: 4, 5, 6, 6.
If a value exceeds this width, the last characters need to be cut off. So
for example:
124891, difference, 22.348, montreal
the strings that need to be printed ought to be:
1248 diffe 22.348 montre
I am thinking I need to do something in the constructor that forces a
string not to exceed a certain number of characters. I will probably
cast the doubles and ints to a string, so I can enforce the maximum width
requirements.
I don't know which method does this or if a string can be instantiated to
behave taht way. Using the formatter only helps with the
fixed-with formatting for printing the string, but it does not actually
chop characters that exceed the maximum length.
You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So
System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");
will produce
'abc' ' a'
(you can remove quotes, obviously).
Use this to cut off the non needed characters:
String.substring(0, maxLength);
Example:
String aString ="123456789";
String cutString = aString.substring(0, 4);
// Output is: "1234"
To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
If you want your integers and doubles to have a certain length then I suggest you use NumberFormat to format your numbers instead of cutting off their string representation.
For readability, I prefer this:
if (inputString.length() > maxLength) {
inputString = inputString.substring(0, maxLength);
}
over the accepted answer.
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
You can use the Apache Commons StringUtils.substring(String str, int start, int end) static method, which is also null safe.
See: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#substring%28java.lang.String,%20int,%20int%29
and http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.1961
You can achieve this easily using
shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
If you just want a maximum length, use StringUtils.left! No if or ternary ?: needed.
int maxLength = 5;
StringUtils.left(string, maxLength);
Output:
null -> null
"" -> ""
"a" -> "a"
"abcd1234" -> "abcd1"
Left Documentation
The solution may be java.lang.String.format("%" + maxlength + "s", string).trim(), like this:
int maxlength = 20;
String longString = "Any string you want which length is greather than 'maxlength'";
String shortString = "Anything short";
String resultForLong = java.lang.String.format("%" + maxlength + "s", longString).trim();
String resultForShort = java.lang.String.format("%" + maxlength + "s", shortString).trim();
System.out.println(resultForLong);
System.out.println(resultForShort);
ouput:
Any string you want w
Anything short
Ideally you should try not to modify the internal data representation for the purpose of creating the table. Whats the problem with String.format()? It will return you new string with required width.
If a string is a = 000102.45600. I need to convert it to a = ---102.45600.
Any help in java using either regex or String formatter?
Tried the following:
a = a.replaceFirst("^0+(?!$)","-");
but i am getting only a = -102.45600 not 3 dashes.
Rules: Any leading zeros before decimal in string should be replaced by that many dashes.
000023.45677 to ----23.45677
002345.56776 to --2345.56776
00000.45678 to -----.45678
Hopefully I am clear on what my need is?
String subjectString = "000102.45600";
String resultString = subjectString.replaceAll("\\G0", "-");
System.out.println(resultString); // prints ---102.45600
\G acts like \A (the start-of-string anchor) on the first iteration of replaceAll(), but on subsequent passes it anchors the match to the spot where the previous match ended. That prevents it from matching zeroes anywhere else in the string, like after the decimal point.
See: reference SO answer.
This should do it:
String number = //assign a value here
for (int i=number.length();i>0; i--) {
if (number.substring(0,i).matches("^0+$")) {
System.out.println(number.replaceAll("0","-"));
break;
}
}
This searches for the longest substring of number which starts at index 0 and consists entirely of zeroes - starting by checking the entire String, then shortening it until it finds the longest substring of leading zeroes. Once it finds this substring, it replaces each zero with a dash and breaks out of the loop.
Why not convert the start of the string to the "." to an integer, convert it back to a string then compare the lengths. 000102 length = 6. 102 length = 3. You would have your preceding zero count.
Integer str = 300;
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(seek);
file.write(Integer.parseInt(String.format("%02x", Integer.reverseBytes(str)), 10));
file.close();
java.lang.NumberFormatException: For input string: "2c010000"
How can save this value in the file?
When you give String.format("%02x",...), you are telling the compiler to give you a Hexadecimal number.
But then you are trying to parse it as a decimal number. Hence the issue.
You should do either of these,
file.write(Integer.parseInt(String.format("%02d", Integer.reverseBytes(str)), 10));
or,
file.write(Integer.parseInt(String.format("%02x", Integer.reverseBytes(str)), 16));
You can skip formatting and parsing, and go straight for this implementation:
file.write(Integer.reverseBytes(str));
The problem is that you are printing the number as hex, but you parse it back as a decimal. To parse the number back as hex, pass 16 for the last parameter of parseInt:
file.write(Integer.parseInt(String.format("%02x", Integer.reverseBytes(str)), 16));
// ^^
Demo.
Note: This is probably not what you want anyway: if you with to write all four bytes, not the MSB, do this:
byte[] bytes = ByteBuffer
.allocate(4)
.putInt(Integer.reverseBytes(str))
.array();
file.write(bytes);
I seem to be going around in circles with this one... There are many methods to achieve this and I could use a few if statements like I've done int he example below, but I want a smarter method.
Problem
The user is asked to input a value in hex, the program grabs this string and will now want to convert it into an integer, bearing in mind this is a hex value. The input could be for example:
0x00
0xf
ff
2
My Attempt
String hexString = response.getResult(); //grabs the user input
int hexInt = Integer.decode(hexString); //Doesn't work if the user doesn't add "0x" at the start
String regex = "\\s*\\b0x\\b\\s*";
String hexInt = hexString.replaceAll(regex, ""); //Doesn't like 0x for some reason
Int hexInt = Integer.valueOf(hexString,16); //Doesn't like 0x
Any ideas on how to do this smartly?
Why not just remove 0x if the string starts with it? There's no need to use a regular expression for this - just a combination of startsWith and substring is simpler to understand (IMO):
String hexString = response.getResult();
if (hexString.startsWith("0x")) {
hexString = hexString.substring(2);
}
int value = Integer.parseInt(hexString, 16);
Thanks in advance for your patience. This is my problem.
I'm writing a program in Java that works best with a big set of different characters.
I have to store all the characters in a String. I started with
private static final String values = "0123456789";
Then I added A-Z, a-z and all the commons symbols.
But they are still too few, so I tought that maybe Unicode could be the solution.
The problem is now: what is the best way to get all the unicode characters that can be displayed in Eclipse (my algorithm will probably fail if there are unrecognized characters - those displayed like little rectangles). Is it possible to build a string (or some strings) with all the characters present here (en.wikipedia.org/wiki/List_of_Unicode_characters) correctly displayed?
I can do a rough copy-paste from http://www.terena.org/activities/multiling/euroml/tests/test-ucspages1ucs.html or http://zenoplex.jp/tools/unicoderange_generator.html, but I would appreciate some cleaner solution.
I don't know if there is a way to extract characters fron a font (the Unifont one). Or maybe I should parse this (www. utf8-chartable.de/unicode-utf8-table.pl) webpage.
Moreover, by adding all the characters into a String I will probably get the error:
"The type generates a string that requires more than 65535 bytes to encode in Utf8 format in the constant pool" (discussed in this question on SO: /questions/10798769/how-to-process-a-string-with-823237-characters).
Hybrid solutions can be accepted. I can remove duplicates following this question on SO questions/4989091/removing-duplicates-from-a-string-in-java)
Finally: every solution to get the longest only-different-characters string is accepted.
Thanks!
You are mixing some things up. The question whether a character can be displayed in Eclipse depends on the font you have chosen; and whether the source file can be processed correctly depends on which character encoding you have set up for the source file. When choosing UTF-8 and a good unicode font you can use and display almost any character, at least more than fit into a single String literal.
But is it really required to show the character in Eclipse? You can use the unicode escapes, e.g. \u20ac to refer to characters, regardless of whether they can be displayed or if the file encoding can handle them.
And if it is not a requirement to blow up your source code, it’s easy to create a String containing all existing characters:
// all chars (i.e. UTF-16 values)
StringBuilder sb=new StringBuilder(Character.MAX_VALUE);
for(char c=0; c<Character.MAX_VALUE; c++) sb.append(c);
String s=sb.toString();
// if it should behave like a compile-time constant:
s=s.intern();
or
// all unicode characters (aka code points)
StringBuilder sb=new StringBuilder(2162686);
for(int c=0; c<Character.MAX_CODE_POINT; c++) sb.appendCodePoint(c);
String s=sb.toString();
// if it should behave like a compile-time constant:
s=s.intern();
If you wan’t the String to contain valid unicode characters only you can use if(Character.isDefined(c)) … inside the loop. But that’s a moving target— newer JRE’s will most probably know more defined characters.
Smply use Apache classes, org.apache.commons.lang.RandomStringUtils (commons-lang) can solve your purpose.
http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/RandomStringUtils.html
Also please refer to below code for api usage,
import org.apache.commons.lang3.RandomStringUtils;
public class RandomString {
public static void main(String[] args) {
// Random string only with numbers
String string = RandomStringUtils.random(64, false, true);
System.out.println("Random 0 = " + string);
// Random alphabetic string
string = RandomStringUtils.randomAlphabetic(64);
System.out.println("Random 1 = " + string);
// Random ASCII string
string = RandomStringUtils.randomAscii(32);
System.out.println("Random 2 = " + string);
// Create a random string with indexes from the given array of chars
string = RandomStringUtils.random(32, 0, 20, true, true, "bj81G5RDED3DC6142kasok".toCharArray());
System.out.println("Random 3 = " + string);
}
}