Generate random string of 300 bytes in Java? - java

I always gets confused when people ask me to generate random string which is of 300 bytes or some predefined bytes. I am not sure what does they mean in general? Are they asking that string should be of 300 length?
I am working on a project in which people have asked me to generate random String of approximately 300 bytes.
Is it possible to do? I am confuse how we can generate random string of 300 bytes?
I know how to generate random string like this -
private static final Random random = new Random();
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public static String generateString(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
}
return sb.toString();
}
Can anyone explain me what does it mean when we need to generate random string of approx 300 bytes?

Strings are made of characters, but the number of bytes required to represent a character can be 1 or 2 (or sometimes more) depending on the character and the encoding. eg characters encoded in UTF8 that are over ascii 127 need 2 bytes, but those under - like english letters and numbers, take only 1.
Normally, string size refers to the number of characters. You only need the bytes if you are writing bytes, and the bytes you write depend on the encoding used.
I would interpret the requirement as 300 characters, especially since you have listed all candidate characters and they are 1-byte chars in the standard encoding.

Since each hexadecimal digit represents four binary digits, which means two digits represent 1 byte. You can generate 300 random numbers Yi in hexadecimals. Such that, 0x41 <= Yi <= 0x5a. so that Yi maps to [A-Za-z] in UTF-8. (Change the range if you want to include numbers or any other characters).
and then you convert these numbers to String using Byte Encodings

A java char is 2 bytes, the example is as follows:
public class Main {
public static void main(String[] args) {
String str="Hello World" ;
System.out.println(str.getBytes().length);
}
}
The result is 11 .

Related

(JAVA) convert decimal to Binary coded decimal?

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.

How many bytes of English and Chinese characters take in java?

import java.io.UnsupportedEncodingException;
public class TestChar {
public static void main(String[] args) throws UnsupportedEncodingException {
String cnStr = "龙";
String enStr = "a";
byte[] cnBytes = cnStr.getBytes("UTF-8");
byte[] enBytes = enStr.getBytes("UTF-8");
System.out.println("bytes size of Chinese:" + cnBytes.length);
System.out.println("bytes size of English:" + enBytes.length);
// in java, char takes two bytes, the question is:
char cnc = '龙'; // will '龙‘ take two or three bytes ?
char enc = 'a'; // will 'a' take one or two bytes ?
}
}
Output :
bytes size of Chinese:3
bytes size of English:1
Here, My JVM is set as UTF-8, from the output, we know Chinese character '龙' takes 3 bytes, and English character 'a' takes one byte. My question is:
In Java, char takes two bytes, here, char cnc = '龙'; char enc = 'a'; will cnc only takes two bytes instead of 3 bytes ? And 'a' takes two bytes instead of one byte ?
The codepoint value of 龙 is 40857. That fits inside the two bytes of a char.
It takes 3 bytes to encode in UTF-8 because not all 2-byte sequences are valid in UTF-8.
UTF-8 is a variable-length character encoding, where characters take up 1 to 4 bytes.
A Java char is 16 bits. See 3.1 Unicode in the Java Language Specification to understand how exactly Java handles Unicode.
Internally, Strings/chars are UTF-16, so it'll be the same for both: Each char will be 16bits.
byte[] cnBytes = cnStr.getBytes("UTF-8");
UTF-8 is a variable length encoding, so the Chinese char takes more bits because it's out of the ASCII character range.

How to generate a random numeric string + random char string and combine?

What I'm trying to do is to generate a random string of numbers E.G 2645237 and one char in a string in the range of A-Z E.G. W and combine the two strings to make 2645237W. I can generate a random number no problem. What I'm stuck on is: 1. Generating a random Char as a string. 2. Combining the two strings to create one string. To be clear what it's for is a school assignment to achieve some extra credit in my marking. Like always I'm not looking for the full answer. Some pseudo-code or a working example would be fine but I'd like the final "A-HA!" moment to be my own doing. A final parameter. This end result (the one string) would need to be a generated 50 times differently (I can do this) and then used as a sort of password. (Meant to replicate a PPS number, the added char is the bit that has my whole class stumped).
I'm not looking to cheat my way to a coded answer, just stuck on this problem (We've all been there)
You can generate a random character simply by doing 'a' (or 'A' for upper case) and then generating a random number from 0 to 25 and adding that to it. i.e. 'a'+3 is 'd'. Note the use of a single quote character to say this is a char literal as opposed to the double quote for a String literal.
That random character can then be appended to the string. StringBuilder would do it for you easily, I'm not sure off hand what the String + operator will do with it.
Try,
Random rn = new Random();
int range = 9999999 - 1000000 + 1;
int randomNum = rn.nextInt(range) + 1000000; // For 7 digit number
System.out.println(randomNum);
Random rc = new Random();
char c = (char)(rc.nextInt(26) + 'A');
System.out.println(c);
String str = randomNum+""+c;
System.out.println(str);
str prints like 1757217Y
To generate the letter and append on your number sequence:
String msg1 = "random number sequence";
Random gen = new Random();
char c = (char) (65 + gen.nextInt(26));
StringBuilder sb = new StringBuilder();
sb.append(msg1);
sb.append(c);
String result = sb.toString();
System.out.println(result);
By the way, 65 is the ascii code of the letter 'A' and gen.nextInt(26) generates a number between 0 and 25, ie, we have a range between 65 and 90 which are the letters' A'-'Z' in ascii table

how to reduce length of UUID generated using randomUUID( )

I have a short utility in which I am generating a UUID using randomUUID().
String uuid = UUID.randomUUID().toString();
However, the uuid generated is too long which is 36 in length.
Is there any way I can reduce the length of the UUID from 36 to near 16 or make the UUID length dynamic?
If you don't need it to be unique, you can use any length you like.
For example, you can do this.
Random rand = new Random();
char[] chars = new char[16];
for(int i=0;i<chars.length;i++) {
chars[i] = (char) rand.nextInt(65536);
if (!Character.isValidCodePoint(chars[i]))
i--;
}
String s = new String(chars);
This will give you almost the same degree of randomness but will use every possible character between \u0000 and \ufffd
If you need printable ASCII characters you can make it as short as you like but the likelihood of uniqueness drops significantly. What can do is use base 36 instead of base 16
UUID uuid = UUID.randomUUID();
String s = Long.toString(uuid.getMostSignificantBits(), 36) + '-' + Long.toString(uuid.getLeastSignificantBits(), 36);
This will 26 characters on average, at most 27 character.
You can use base64 encoding and reduce it to 22 characters.
If you use base94 you can get it does to 20 characters.
If you use the whole range of valid chars fro \u0000 to \ufffd you can reduce it to just 9 characters or 17 bytes.
If you don't care about Strings you can use 16, 8-bit bytes.
String uuid = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
String uuid16digits = uuid.substring(uuid.length() - 16);
This will return the last 16 digits of actual uuid.
Convert it from base 16(0-9,A-F) to base 36(0-9,A-Z).. You could go to base 62 (0-9, A-Z, a-z) but if you need to read it over a phone or something then this can be error prone.
https://github.com/salieri/uuid-encoder is a lib that might work for you...
Also this means you still have a GUID -you haven't truncated it like the other answers
You can use the substring method to decrease the string length while generating uuid.
UUID.randomUUID().toString().substring(0, 5)
You could evaluate using the ${__time()} function
The following snippet is a dynamic UUID code. By default, the legth of the UUID depends on bits but the function randomly chooses characters from the UUID
public String myUUID(int length) {
String allChars = UUID.randomUUID().toString().replace("-", "");
Random random = new Random();
char[] otp = new char[length];
for (int i = 0; i < length; i++) {
otp[i] =
allChars.charAt(random.nextInt(allChars.length()));
}
return String.valueOf(otp);
}
Yes,You can create by using this function.
public static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes()).getLong();
return Long.toString(l, Character.MAX_RADIX);
}

Creating a random string with only certain letters and a certain length

So I want to generate a random string but only want certain characters to be the string (Only ones that can be used in a file name to be hosted so something like www.example.com/HERE.EXTENTION).
So how can I make a random string that is a length that I want with only certain letters I want.
I know I can do a for look from the length, and then use the random number and cast that to a char and add it to a string. But I don't want characters that I don't want to be added and going through a loop with all that I don't want because that would take too long.
Use this quick method:
String genRand(int length){
Random rand=new Random();
String possibleLetters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.";
StringBuilder sb = new StringBuilder(length);
for(int i = 0; i < length; i++)
sb.append(possibleLetters.charAt(rand.nextInt(possibleLetters.length())));
return sb.toString();
}
Edit possibleLetters to include the characters you want. Note that \ and newlines must be escaped.
Store all your accepted letters in an array, then generate a random number between 0 and the length of this array N times, to get N indices of a letter in the array. Concatenate the letters.
EDIT:
Note that if your goal is to generate unique names, random is not the solution. A random doesn't guarantee uniqueness.
Other than the two answers -
You can have it like <yourChoiceOfName>-<currentTime>.yourext. This way the chances of two files with the same name is lesser.
The currenttime could include milliseconds.
In this case you have a known length i.e. length of yourChoiceOfName + length of currentTime + lenght of yourext.

Categories

Resources