So I have a set of base digits like "BCDFGHJKLMNPQRSTVWXZ34679"
how do I convert a value say "D6CN96W6WT" to binary string in Java?
This should work (assuming 0,1 for you binary digits):
// your arbitrary digits
private static final String DIGITS = "BCDFGHJKLMNPQRSTVWXZ34679";
public String base25ToBinary(String base25Number) {
long value = 0;
char[] base25Digits = base25Number.toCharArray();
for (char digit : base25Digits) {
value = value * 25 + DIGITS.indexOf(digit);
}
return Long.toString(value, 2);
}
Off the top of my head, for base-25 strings.
Integer.toString(Integer.valueof(base25str, 25), 2)
Its a little unclear from your question whether you're talking about actual 0-9-Z bases, or a number encoding with an arbitrary list of symbols. I'm assuming the first, if its the later then you're out of luck on built-ins.
Related
As stated in the title, I would like to write a double in a string with a maximum number of character, in java.
Well actually to an exact number of character, but I can wrap it in a String.format("%Xs", ...) with given X to fill missing character.
Note that there are many questions related to this on SO and internet, but I couldn't find the exact same as mine for java.
What I think of would be to write
the full double if it fits: for max character n=10, 123.4567 is good
round decimal and keep the integer part if it fits: for n=10, 123456.789654 would format to 123456.79
use exponential otherwise: for n=10, 123456789123.321654 would format to 1.23457e11
=> Is there a practical tool to do that or something equivalent?
That is what I have for now, not perfect but I spend enough time on it already.
The idea is that Double.toString is doing exactly what I want but for a fixed length (maybe someone knows how to configure that length?). So I use it and remove decimal when necessary
/** write a double to a string of exact given length (but for some extreme cases) */
public static String doubleToString(double x, int length) {
String str = Double.toString(x);
if(str.length() <= length){
return org.apache.commons.lang.StringUtils.repeat(" ", length - str.length()) + str;
} else if(str.contains("E")){
String[] split = str.split("E");
String num = split[0];
String exp = split[1];
return removeDecimal(num, length - exp.length()-1) + 'E' + exp;
} else {
return removeDecimal(str, length);
}
}
// remove trailing decimal of a double as string such as xxx.yyyy
private static String removeDecimal(String doubleStr, int length){
int dotIndex = doubleStr.indexOf('.');
return doubleStr.substring(0, Math.max(dotIndex+1, length));
}
Take a look at BigDecimal (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html) I use new DecimalFormat("0.00") if I want to ensure that the two decimal places are always shown, e.g. 1000.5 will display as 1000.50.
I'm learning JAVA and recently I had the same problem with a few training tasks.
I have a some numbers and some of them are starting with 0. I found out that these numbers are octal which means it won't be the number I wanted or it gives me an error (because of the "8" or the "9" because they are not octal digits) after I read it as an int or long...
Until now I only had to work with two digit numbers like 14 or 05.
I treated them as Strings and converted them into numbers with a function that checks all of the String numbers and convert them to numbers like this
String numStr = "02";
if(numStr.startsWith("0")) {
int num = getNumericValue(numStr.charAt(1));
} else {
int num = Integer.parseInt(numStr);
}
Now I have an unkown lot of number with an unknown number of digits (so maybe more than 2). I know that if I want I can use a loop and .substring(), but there must be an easier way.
Is there any way to simply ignore the zeros somehow?
Edit:
Until now I always edited the numbers I had to work with to be Strings because I couldn't find an easier way to solve the problem. When I had 0010 27 09 I had to declare it like:
String[] numbers = {"0010", "27", "09"};
Because if I declare it like this:
int[] numbers = {0010, 27, 09};
numbers[0] will be 8 instead of 10 and numbers[2] will give me an error
Actually I don't want to work with Strings. What I actually want is to read numbers starting with zero as numbers (eg.: int or long) but I want them to be decimal. The problem is that I have a lot of number from a source. I copied them into the code and edited it to be a declaration of an array. But I don't want to edit them to be Strings just to delete the zeros and make them numbers again.
I'm not quite sure what you want to achieve. Do you want to be able to read an Integer, given as String in a 8-based format (Case 1)? Or do you want to read such a String and interpret it as 10-based though it is 8-based (Case 2)?
Or do you simply want to know how to create such an Integer without manually converting it (Case 3)?
Case 1:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 8-based integer.
Integer number = Integer.parseInt(input, 8);
Case 2:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 10-based integer (default).
Integer number = Integer.parseInt(input);
Case 3:
// Java interprets this as octal number
int octal = 0235;
// Java interprets this as hexadecimal number
int hexa = 0x235
// Java interprets this as decimal number
int decimal = 235
You can expand Case 1 to a intelligent method by reacting to the indicator:
public Integer convert(final String input) {
String hexaIndicator = input.substring(0, 2);
if (hexaIndicator.equals("0x")) {
return Integer.parseInt(input.substring(2), 16);
} else {
String octaIndicator = input.substring(0, 1);
if (octaIndicator.equals("0")) {
return Integer.parseInt(input.substring(1), 8);
} else {
return Integer.parseInt(input);
}
}
}
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 am trying to get the last two and first two digits from a number. I am getting a really weird result with the return value of my lastTwo function.
public static int lastTwo(int digit){
String str = Integer.toString(digit);
String lastTwo = str.substring(str.length()-2);
int response = Integer.parseInt(lastTwo);
return response;
}
When the input digit is 104, the output of this is just 4, but when the input is 114, the output is 14 which is the correct output. Why is substring on 104 not returning a 0 in the correct place?
here is my bluej console just for extra visuals:
twoDigit.main({ }) (104)
4
10
twoDigit.main({ }) (114)
14
10
Your code is doing the splitting correctly, but primitive ints are not stored with leading zeroes; you can just return the String instead of Integer.parseing it back to an int. e.g.
public static int lastTwoAsString(int digit){
String str = Integer.toString(digit);
String lastTwo = str.substring(str.length()-2);
return lastTwo;
}
If you indeed want to parse it back to an int, Java won't print leading zeroes by default. However, you can print leading zeroes of an int using use String.format. Note that you must specify a width to use the 0 modifier, in this case 2 makes the most sense:
public static void main(String[] args) {
int value = lastTwo(104);
String output = String.format("%02d", value);
System.out.println(output);
}
Output:
04
The last two digits of "104" is "04".
Then, the result of Integer.parseInt("04") is 4, because as an integer, the value of "04" is simply 4. And if you print the number 4, it's naturally printed as "4".
But why do you call Integer.parseInt at all?
The problem description seems underspecified.
It's not clear if the last two digits should be treated as a number or as a string.
If the last two digits should be a string, then your method should return a string.
If the last two digits should be a number, then instead of converting the input int to a String, it would be better to use the modulo operator:
static int lastTwo(int number) {
return number % 100;
}
static String lastTwoAsString(int number) {
String string = Integer.toString(number);
return string.substring(string.length() - 2);
}
The current method signature returns an int. As such, it cannot return 02. You will have to change it to String or format the output where the method is called.
If you can change the return type to String, you can do:
First way:
public static String lastTwo(int digit) {
String str = String.valueOf(digit);
return = str.substring(str.length() - 2);
}
Otherwise, where you call the method, you can format it:
String.format("%02d", lastTwo(digit))
I want to hash a word into fixed bit hash value say 64 bit,32 bit (binary).
I used the following code
long murmur_hash= MurmurHash.hash64(word);
Then murmur_hash value is converted into binary by the following function
public static String intToBinary (int n, int numOfBits) {
String binary = "";
for(int i = 0; i < numOfBits; ++i) {
n/=2;
if(n%2 == 0)
{
binary="0"+binary;
}
else
binary="1"+binary;
}
return binary;
}
Is there any direct hash method to convert into binary?
Just use this
Integer.toBinaryString(int i)
If you want to convert into a fixed binary string, that is, always get a 64-character long string with zero padding, then you have a couple of options. If you have Apache's StringUtils, you can use:
StringUtils.leftPad( Long.toBinaryString(murmurHash), Long.SIZE, "0" );
If you don't, you can write a padding method yourself:
public static String paddedBinaryFromLong( long val ) {
StringBuilder sb = new StringBuilder( Long.toBinaryString(val));
char[] zeros = new char[Long.SIZE - sb.length()];
Arrays.fill(zeros, '0');
sb.insert(0, zeros);
return sb.toString();
}
This method starts by using the Long.toBinaryString(long) method, which conveniently does the bit conversion for you. The only thing it doesn't do is pad on the left if the value is shorter than 64 characters.
The next step is to create an array of 0 characters with the missing zeros needed to pad to the left.
Finally, we insert that array of zeros at the beginning of our StringBuilder, and we have a 64-character, zero-padded bit string.
Note: there is a difference between using Long.toBinaryString(long) and Long.toString(long,radix). The difference is in negative numbers. In the first, you'll get the full, two's complement value of the number. In the second, you'll get the number with a minus sign:
System.out.println(Long.toString(-15L,2));
result:
-1111
System.out.println(Long.toBinaryString(-15L));
result:
1111111111111111111111111111111111111111111111111111111111110001
Another other way is using
Integer.toString(i, radix)
you can get string representation of the first argument i in the radix ( Binary - 2, Octal - 8, Decimal - 10, Hex - 16) specified by the second argument.