(JAVA) convert decimal to Binary coded decimal? - java

For example, I would like to convert the int value 12 into a String output of BCD: 00 12 (0x00 0x12).
If I have int value of 256, it will be 02 56 (which is 0x02 0x56),
or if I have a int value of 999, it will be 09 99 (0x09 0x99),
9999 would be 99 99 (0x99 0x99).
Right now, my only solution is to create a String array of size 4, and calculate how many characters are there by converting the int value into String. If there are 2 characters, I will add 2 x 0 into the array first before adding the 2 characters, and then make them back into a single String variable.
Basically,
int value = 12;
String output = Integer.toString(value);
// then count the number of characters in the String.
// 4 minus (whatever number of characters in the String, add zeros
// add the characters:
stringArray[0] = "0";
stringArray[1] = "0";
stringArray[2] = "1";
stringArray[3] = "2";
// then, concatenate them back
If there are 3 characters, I will add one 0 into the array first before adding 3 characters. I was wondering if there is any other way?

You can use String.format to append leading 0 and use substring to split in to two part.
int value = 12;
String output = String.format("%04d",value);
System.out.println(output.substring(0,2)+" "+output.substring(2,4));
String.format("%04d",value) will append 0s in the front if the length is less than 4.
If you do not want to use substring you can use String.split and String.join like below.
System.out.println(
String.join(
" ",
Arrays.asList(
output.split("(?<=\\G.{2})")
)
)
);
output.split("(?<=\\G.{2})") will split the string in 2 characters each.

Is that what you are asking for?
public static String formatTheString(String string, int length) {
return String.format("%"+length+"s", string).replace(' ', '0');
}
and pass the values like
formatTheString(Integer.toString(256),4);

I think what you are asking is not correct.
refer this for BCD.
and below code is sufficient for what you need
System.out.printf("%04d",n);
in above code n is your number.

Related

How to split a string into several strings of equal sizes

I have to convert a binary number to a hex number. The way I have decided to do this is to split the binary string into several strings of length 4 and assign each string its corresponding value in hex number (i.e. 1000 = 8, 1101 = D).
I have seen several question asking for a way to split a string into strings of size 4 the same thing but all of those solutions used a regex that gave a single string. For example I found this line of code in a solution:
System.out.println(Arrays.toString("String".split("(?<=\G.{4})")));
When I tried to use it with the binary number "10011000", I got "[1001, 1000]" but as a single string (the brackets, comma, and blank space were included as characters) and I was left with the same problem, how do I split a string.
Is there a way to split a string into an array of smaller strings?
You can try making the string a char array and then into another array of strings, add each 4 characters of the char array.
Try this:
String BinaryNumber = "10011010";
char[] n = new char[BinaryNumber.length()];
for(int i=0; i<BinaryNumber.length(); i++){
n[i] = BinaryNumber.charAt(i);
}
String str;
String[] NumberArray = new String[(BinaryNumber.length())/4];
int count = 0;
for(int i=0; i<BinaryNumber.length(); i+=4){
str = String.valueOf(n[i])+String.valueOf(n[i+1])+String.valueOf(n[i+2])+String.valueOf(n[i+3]);
NumberArray[count] = str;
count++;
}
I think this might be the solution, though it will only work if the length of the BinaryNumber is divisible by 4.
Try it like this.
String binaryNumber = "110101111";
// first make certain the binary string is a multiple of length four so
// pad on the left with 0 bits.
binaryNumber = "0".repeat(3 - (binaryNumber.length()+3) % 4)
+ binaryNumber;
// Then you can just split it like this as you described.
String[] groups = binaryNumber.split("(?<=\\G.{4})");
for (String v : groups) {
System.out.println(v);
}
prints
0001
1010
1111

Add zeros to the left of Number

I know that I can add left zeros to String but what about Long?
I need to put left zeros until the Long size is 10 digits. For example, if it's 8 digits (12345678), it should add 2 left zeros (0012345678)
I want to add this in the getValue() method.
public Long getValue() {
// Should always be 10 digits, If it's 8, add zeros
return value;
}
I'm using spring. This issue is that the database that cuts the left zeros. Maybe is there a annotation to avoid extra code?
This is not possible. A Long does not contain data about the String representation of its value. In fact, the Long is actually stored in binary, not decimal, and the long object is unaware of this.
If you want to convert it to a String with leading zeroes, String.format("%017d" , number); will pad it to make sure it has 10 digits.
In java, a long (wrapped in a Long) will always be stored on 8 bytes,
There is no way to "add" extra zeros as they're already existing.
Either your database must change its type to String and add padding zeros when you store your Long object either change your inner code to String and add padding zeros when you pull the data from your Long in db.
You cannot because a long does not have a leading zero.
A string of characters like 0012345678 is not an integer, 12345678 is.
but there are two way in java to add leading zeroes
WAY 1: format() method
int number = 9;
String str = String.format("%04d", 9); // 0009
System.out.printf("original number %d, numeric string with padding : %s", 9, str);
WAY 2 : DecimalFormat
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // 0009
String a = df.format(99); // 0099
String b = df.format(999); // 0999
but in both case you get string instead of Long
for more reading
Try this one,
int number = 12345678;
String str = String.format("%10d", number);
System.out.println("original number %d, numeric string with padding : %s", number, str);

Splitting an array by 16 characters then putting each of the parts into an array

It's a very simple problem but at the moment my brain is fried from working on other parts of this project so I need help. I have a string of a size of a multiple of 16(example: size 16, 32, 48 etc.) I need to break that string into smaller strings of length 16 and place them into an array of size string.length()/16
For example we'll say my string(appendSourceBinary) is: "1000101101001001"
Here's my non working code:
String[] holding = new String[appendSourceBinary.length()/16];
int counter;
for(int z = 0; z < appendSourceBinary.length(); z++){
holding[z] = appendSourceBinary.substring(z, z+16);
}
There is a regex to do this just using split:
String[] array = appendSourceBinary.split("(?<=\\G.{16})");
The regex splits on points in the string proceeded (asserted using a look behind) by the end of the last match (\G) followed by 16 characters (.{16}). Conveniently, \G is initially set to start of input.
Some test code:
String appendSourceBinary = "A234567890123456B234567890123456C234567890123456";
String[] array = appendSourceBinary.split("(?<=\\G.{16})");
Arrays.stream(array).forEach(System.out::println);
Output:
A234567890123456
B234567890123456
C234567890123456
You could do it in two lines, without a loop, like this:
String appendSourceBinary = "10101010101010101010101010101010";
String[] split = appendSourceBinary.replaceAll("([01]{16})", "$1x").split("x");
I've used a regular expression search and replace to find each group of sixteen characters in the string and to replace them with themselves followed by an x. Then I've split the string on the x, leaving an array containing the groups of 16 characters.
If you add a simple loop to output the results:
for (int i = 0; i < split.length; i++)
System.out.println(split[i]);
you'll find the output is
1010101010101010
1010101010101010
Which is the original 32 char string I used split in two 16 char strings. Any remainder will be returned as the last element of the array. If there are less than 16 chars in the input string they'll be returned as the first and only array entry.

Android java append n characters to string

I would like to append "0" string when an int is lower than 5. I have tried this
if(allItems_filtered.results(i).min_sale_unit_price.length() < 5){
calc = 5 - allItems_filtered.results(i).min_sale_unit_price.length();
min_sale_unit_price = String.format("%0" + calc + "d", allItems_filtered.results(i).min_sale_unit_price);
}
int calc is the amount of "0" it has to append in front of the min_sale_unit_price string
Which returns this error:
%d can't format java.lang.String arguments
Which is quite self explaining but I do not know how to the the same but then to a string.
It is telling you that you are trying to format a String, but %d is refering to an int, you need to convert the String to int an it will work. Also you don't need to calculate how many zeros you need, if you use %05d it will automatically fill the number till it's length isn't 5
min_sale_unit_price = String.format("%05d", Integer.valueOf(allItems_filtered.results(i).min_sale_unit_price));
Take for an example
Log.d("123?", String.format("%05d", 123));
Will print out
00123
If you take a number that is larger in size than five, it will not append anything
Log.d("123?", String.format("%05d", 123456));
Will result
123456

Java get integer value from string

I'd like to get the integer value from my string. Below is my example.
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
But I just want to get the score which is 10. How can I do this?
UPDATED:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
bfLog.createEntry( firstNumber );
I save this to sqlite database.
You can use one of the String regex replace methods to capture the first digits in a captured group:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
.*? consumes initial non-digits(non-greedy)
(\\d+) Get the one or more available digits in a group!
.* Everything else (greedy).
This depends on whether anything else can change in your string.
If it's always the same apart from the number, you can use
int score = Integer.parseInt(strScore.substring(14,16))
because the digits "10" are at index 14 and 15 of the string.
If other stuff changes in your string, you should use a regular expression :
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
You can try this:
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
String intIndex = strScore.valueOf(10);
String intIndex = 10 // Result

Categories

Resources