This question already has answers here:
Integer to two digits hex in Java
(7 answers)
Closed 1 year ago.
I'm trying to pad a hexadecimal digit with 0's in the beginning so that the length of it is always 4. For example, the FF is going to be padded as 00FF. I have tried to use String.format("%04d", number) but it didn't work as my hexadecimal digit is actually a string.
I have also tried using StringUtils.leftPad() but for some reason, IntelliJ couldn't detect it.
Please note my count is going to change, but I haven't represented it here as I'm yet to implement it. This is my sample code. Thanks.
public static void main(String[] args) {
int count = 0;
String orderID = Integer.toHexString(count).toUpperCase();
System.out.println(String.format("%04d", Integer.valueOf(orderID)));
}
String.format("%04x", 255)
with output
00ff
(or use X for uppercases hex digits)
As #user16320675 point, more info about Formatter here.
Related
This question already has answers here:
Convert an integer to an array of digits
(24 answers)
Closed 2 years ago.
I would just like to ask how to convert an int to int array - for example:
int number = 12345;
to:
[1,2,3,4,5];
Btw - could not really find anything out there, so we may hope that someone know.
thanks in advance
You can do it like this:
int number = 12345;
int[] digits = String.valueOf(number).chars().map(c -> c-'0').toArray();
Explanation:
First convert int to string with String.valueOf(number) to be able to use the method chars() which get a stream of int that represents the ASCII value of each char in the string. Then, we use the map function map(c -> c-'0') to convert the ASCII value of each character to its value, subtracting the value of the ASCII code from the character '0' from the ASCII code of the actual character. Finally, the stream is converted to an array with toArray().
This question already has answers here:
How to generate a random BigInteger value in Java?
(8 answers)
Closed 2 years ago.
I am attempting to generate a random 20 digit BigInteger in Java.
So far, I have been able to generate a fixed length hex value.
// generate a user-specified number of random bytes
public void getRandomNumber(int count) {
byte[] bytes = new byte[count];
new SecureRandom().nextBytes(bytes);
String random = new String(Hex.encode(bytes));
System.out.println(random);
}
This is ideal for a fixed length hex generation. But I struggle to find an efficient method of doing this for a decimal representation; when converting from hex to BigInteger(hexValue, 16), the length will vary.
I have considered trying this by setting upper and lower bounds, or by generating something big enough and trimming to the desired length, but those methods do not feel very clean.
Edit: The solution I have came up with that is working fine in my program:
// generate a random number with specified bit length
public void getTokenID() {
int count = 64;
SecureRandom rnd = new SecureRandom();
BigInteger randomCountLength;
String token;
do {
randomCountLength = new BigInteger(count, rnd);
token = randomCountLength.toString();
} while (token.length() != 20);
Tid = token;
}
What I understand that your problem is to generate random number with fixed length (fixed number of digits)
It is obvious that using hex value will work since any hex digit represent 4 bytes. So when you fix the length of bytes (bytes table in your code) it work fine
What I advice you when dealing with decimal number is :
1- There is methods for generating random number with lower and upper bound, for example Random betwen 5 and 10, so if you want for example a random number with 20 digits , you have to generate random number between (10^19) and (10^20-1)
2- The second is hardcoded method to make a loop of 20 iterations when you generate random digit (between 0 and 9 exept the the digit of strong weight which must be between 1 and 9) and you get the number.
This question already has answers here:
Alphanumeric increment algorithm in JAVA [closed]
(2 answers)
Closed 2 years ago.
I want to implement a functionality that auto increment an alpha numeric id in a Java program.
The ids types are Strings, have only digits and lower case latin letters, and is case insensitive.
Basically, I want a function called static String next(String id) that gives what should be the next id.
The id should increase from right to left, and new characters should be added on the left.
For example
assertEquals("1", IdUtils.next("0"));
assertEquals("a", IdUtils.next("9"));
assertEquals("10", IdUtils.next("z"));
assertEquals("10", IdUtils.next("0z"));
assertEquals("100", IdUtils.next("zz"));
assertEquals("zz1", IdUtils.next("zz0"));
assertEquals("zza", IdUtils.next("zz9"));
Thanks in advance.
A number with digits and lower case latin letters is a base-36 number, which is an extension of base-16, also known as hex.
So to increment the base-36 number, parse it, increment it, and convert back to text.
static String next(String id) {
return Long.toString(Math.incrementExact(Long.parseLong(id, 36)), 36);
}
Test
System.out.println(next("0"));
System.out.println(next("9"));
System.out.println(next("z"));
System.out.println(next("zzzzzz"));
System.out.println(next("dif5613ug"));
System.out.println(next("1y2p0ij32e8e6"));
System.out.println(next("1y2p0ij32e8e7")); // Long.MAX_VALUE, so will overflow
Output
1
a
10
1000000
dif5613uh
1y2p0ij32e8e7
Exception in thread "main" java.lang.ArithmeticException: long overflow
If you're going to have an "current ID" variable that you increment, then it's better to keep that state in an AtomicLong instead of a String. It's faster, and much easier to make thread-safe:
...
AtomicLong m_nextId = new AtomicLong();
static String next() {
long idnum = m_nextId.getAndIncrement();
return Long.toString(idnum,36);
}
This question already has answers here:
Get a specific digit of a number from an int in Java [duplicate]
(4 answers)
Closed 3 years ago.
How to extract the hundred of an int variable?
For example, I have a random number:
int i = 5654217;
I want code to extract the number "2".
I tried to do
i/100
Which gave me 56542.
But I can't find a way to extract only the last number.
Too, I'm really unsure this is the best way to extract the hundred of the variable.
I am not 100% sure what you are asking so I will put the two guesses that I have of what your question is. If it doesn't answer your question please feel free to let me know, I will help you.
1) You are dividing an integer (int) by 100 and the last 2 digits disappear.
double x = (double)i/100.0;
//ints cannot store a decimal
2) You have a decimal (double) and are trying to output hundreds digit.
public int hundredthsDigit(double x){
if(x>0.0) return (x/100)%10;
//This moves the 100s digit to the 1s digit and removes the other digits by taking mod 10
return 10-Math.abs(x/100)%10;
// does practically the same thing, but is a work around as mod doesn't work with negatives in java
}
The modulus operator, % effectively gives you the remainder of a division.
You can get the last digit by getting the number, mod 10. Try (i / 100) % 10
You can read up more on modular arithmetic and such here: https://en.m.wikipedia.org/wiki/Modular_arithmetic
Please find code below:
package com.shree.test;
public class FindNumber {
public static int findNumberAt(int location,int inputNumber) {
int number = 0;
//number = (inputNumber % (location*10))/location; // This also works
number = (inputNumber/location)%10; // But as mentioned in other comments and answers, this line is perfect solution
return number;
}
public static void main(String[] args) {
System.out.println(findNumberAt(100, 5654217));
}
}
This question already has answers here:
How does a leading zero change a numeric literal in Java?
(3 answers)
Closed 7 years ago.
How does this snippet of code prints "-511" as the output on the console?
class Test
{
public static void main(String[] args) {
int i = -0777;
System.out.printf("%d",i);
}
}
Is it to do with the way Java stores Negative numbers?
Integer numbers prefixed with 0 are octal numbers. To use decimal numbers remove the 0 prefix:
int i = -777;
Numbers starting with 0 are treated as being in octal by Java. -077 is equivalent to -63, which is what I get when I run your program.
When a number in java code starts with a 0, it interprets it as octal format