Flip a Hex String - java

Acording to a other question made here Split a Hex String without spaces and flip it, I write this new question more clearly here.
I have an Hex String like this:
Hex_string = 2B00FFEC
What I need is to change the order of the Hex String to start from the latest characters, so this would be like this:
Fliped_hex_string = ECFF002B
In the other question I asked a way to achieve this using the .split() method. But there should be another way to get this in a better way.

As simple as you can is
String s = "2B00FFEC";
StringBuilder result = new StringBuilder();
for (int i = 0; i <=s.length()-2; i=i+2) {
result.append(new StringBuilder(s.substring(i,i+2)).reverse());
}
System.out.println(result.reverse().toString()); //op :ECFF002B

OP constrains the character length to exactly 8 characters in comments.
A purely numeric answer (inspired from idioms to convert endianness); saves going to and from strings
n is an int:
int m = ((n>>24)&0xff) | // byte 3 to byte 0
((n<<8)&0xff0000) | // byte 1 to byte 2
((n>>8)&0xff00) | // byte 2 to byte 1
((n<<24)&0xff000000); // byte 0 to byte 3
If you need to convert this to hexadecimal, use
String s = Integer.toHexString(m);
and if you need to set n from hexadecimal, use
int n = (int)Long.parseLong(hex_string, 16);
where hex_string is your initial string. You need to go via the Long parser to allow for negatives.

You could do something like:
String a = "456789AB";
char[] ca = a.toCharArray();
StringBuilder sb = new StringBuilder(a.length());
for (int i = 0; i<a.length();i+=2)
{
sb.insert(0, ca, i, 2);
}
This also extends to longer Strings if needed

Perhaps you should try something as simple as this:
public static String flip(final String hex){
final StringBuilder builder = new StringBuilder(hex.length());
for(int i = hex.length(); i > 1; i-=2)
builder.append(hex.substring(i-2, i));
return builder.toString();
}
public static void main(String args[]){
System.out.println(flip("2B00FFEC"));
}
The output is: ECFF002B
Next time you ask a question, perhaps you should show us some code you've written used in order to solve your problem (and then ask us why your code doesn't work, not your problem). You will not learn anything from us just providing answers without you knowing how they work.

This method seems to do what you want
String changeHexOrder(String s) {
char[] arr = s.toCharArray();
char tmp;
//change positions of [i, i + 1 , , , , , ,length - i - 2, length - i - 1]
for (int i = 0; i < arr.length / 2; i += 2) {
tmp = arr[i];
arr[i] = arr[arr.length-i-2];
arr[arr.length-i-2] = tmp;
tmp = arr[i+1];
arr[i+1] = arr[arr.length-i-1];
arr[arr.length-i-1] = tmp;
}
return new String(arr);
}

This worked for me
StringBuilder lsbToMsb=new StringBuilder();
for(int i=input.length();i>0;i-=2)
{
lsbMsb.append(lsbToMsb.substring(i-2,i));
}
String lsbMsb=lsbMsb.toString();

Related

Best way to concatenate Strings in java(Time efficiency)

I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA", how can we concatenate it with n times the char '_',knowing that the '_' has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA", the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1:
As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
public class Concatenation {
public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Go to char array, alloting the right size, fill the array, and sum it up back into a string.
Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW:
Actual answer to the question is in the code of that repeat method.
when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.

Java - Help converting letter to integer, adding 5, then converting back to letter

First off, here is my code so far
public int encrypt() {
/* This method will apply a simple encrypted algorithm to the text.
* Replace each character with the character that is five steps away from
* it in the alphabet. For instance, 'A' becomes 'F', 'Y' becomes '~' and
* so on. Builds a string with these new encrypted values and returns it.
*/
text = toLower;
encrypt = "";
int eNum = 0;
for (int i = 0; i <text.length(); i++) {
c = text.charAt(i);
if ((Character.isLetter(c))) {
eNum = (int) - (int)'a' + 5;
}
}
return eNum;
}
(text is the inputted string by the way. And toLower makes the string all lower case to make it easier converting.)
I got most of my assignment done, but one part of it is tasking me with moving every letter inputted 5 spaces over. A becomes F, B becomes G, etc.
So far from I got the letter converted to a number, but I am having trouble adding to it and then returning it back to a letter.
When I run the program and I enter my input such as "abc" I get '8'. It just adds them all up.
Any help would be much appreciated, and I can post the full code if necessary.
Few issues -
First of all - eNum = (int) - (int)'a' + 5; you do not need the first (int) - i believe, you can just do - eNum = (int)c + 5; . Your expression would always result in a negative integer.
Instead of returning eNum you should convert it to character and add it to a string and return the string at end (or you can create a character array of same length as string , keep storing the characters in the array, and return a string created from the character array).
Instead of using a in the condition , you should use c which denotes the current character at the ith index.
I am guessing not all of the variables in your code are member variables (instance variables) of the class , so you should define them with a datatype in your code.
Example changes to your code -
String text = toLower; //if toLower is not correct, use a correct variable to get the data to encrypt from.
String encrypt = "";
for (int i = 0; i <text.length(); i++) {
char c = text.charAt(i);
if ((Character.isLetter(c))) {
encrypt += (char)((int)c + 5);
}
}
return encrypt;
//Just a quick conversion for testing
String yourInput = "AbC".toLowerCase();
String convertedString = "";
for (int i = 0; i <text.length(); i++) {
char c = yourInput.charAt(i);
int num = Character.getNumericValue(c);
num = (num + 5)%128 //If you somehow manage to pass 127, to prevent errors, start at 0 again using modulus
convertedString += Integer.toString(num);
}
System.out.println(convertedString);
Hope this is what you're looking for.
Try something like this, I believe this has several advantages:
public String encrypt(String in) {
String workingCopy = in.toLowerCase();
StringBuilder out = new StringBuilder();
for (int i = 0; i < workingCopy.length(); i++) {
char c = workingCopy.charAt(i);
if ((Character.isLetter(c))) {
out.append((char)(c + 5));
}
}
return out.toString();
}
This code is a little bit verbose, but perhaps then it is easier to follow. I introduced the StringBuilder because it is more efficient than doing string = string + x

Removing duplicates from a string

I am trying to remove duplicates from a String in Java. Here i what I have tried
public void unique(String s)
{
// put your code here
char[]newArray = s.toCharArray();
Set<Character> uniquUsers = new HashSet<Character>();
for (int i = 0; i < newArray.length; i++) {
if (!uniquUsers.add(newArray[i]))
newArray[i] =' ';
}
System.out.println(new String(newArray));
}
Problem with this is when I try to remove the duplicate I replace it with a space. I tried replacing the duplicate with '' but it cannot be done or I cant set the duplicate place to null. What is the best way to do this?
If you use regex, you only need one line!
public void unique(String s) {
System.out.println(s.replaceAll("(.)(?=.*\\1)", ""));
}
This removes (by replacing with blank) all characters that found again later in the input (by using a look ahead with a back reference to the captured character).
If I understand your question correctly, perhaps you could try something like:
public static String unique(final String string){
final StringBuilder builder = new StringBuilder();
for(final char c : string.toCharArray())
if(builder.indexOf(Character.toString(c)) == -1)
builder.append(c);
return builder.toString();
}
You can use BitSet
public String removeDuplicateChar(String str){
if(str==null || str.equals(""))throw new NullPointerException();
BitSet b = new BitSet(256);
for(int i=0;i<str.length();i++){
b.set(str.charAt(i));
}
StringBuilder s = new StringBuilder();
for(int i=0;i<256;i++){
if(b.isSet(i)){
s.append((char)i);
}
}
return s.toString();
}
You can roll down your own BitSet like below:
class BitSet {
int[] numbers;
BitSet(int k){
numbers = new int[(k >> 5) + 1];
}
boolean isSet(int k){
int remender = k & 0x1F;
int devide = k >> 5;
return ((numbers[devide] & (1 << remender)) == 1);
}
void set(int k){
int remender = k & 0x1F;
int devide = k >> 5;
numbers[devide] = numbers[devide] | (1 << remender);
}
}
This will work for what you are attempting.
public static void unique(String s) {
// r code here
char[] newArray = s.toCharArray();
Set<Character> uniqueUsers = new HashSet<>();
for (int i = 0; i < newArray.length; i++) {
uniqueUsers.add(newArray[i]);
}
newArray = new char[uniqueUsers.size()];
Iterator iterator = uniqueUsers.iterator();
int i = 0;
while (iterator.hasNext()) {
newArray[i] = (char)iterator.next();
i++;
}
System.out.println(new String(newArray));
}
without changing almost anything in your code, change the line
System.out.println(new String(newArray));
for
System.out.println( new String(newArray).replaceAll(" ", ""));
the addition of replaceAll will remove blanks
import java.util.*;
class StrDup{
public static void main(String[] args){
String s = "abcdabacdabbbabbbaaaaaaaaaaaaaaaaaaabbbbbbbbbbdddddddddcccccc";
String dup = removeDupl(s);
}
public static String removeDupl(String s){
StringBuilder sb = new StringBuilder(s);
String ch = "";
for(int i = 0; i < sb.length(); i++){
ch = sb.substring(i,i+1);
int j = i+1;
int k = 0;
while(sb.indexOf(ch,j)!=-1){
k = sb.indexOf(ch,j);
sb.deleleCharAt(k);
j = k;
}
}
return sb.toString();
}
}
In the code above, I'm doing the following tasks.
I'm first converting the string to a StringBuilder. Strings in Java are immutable, which means they are like CDs. You can't do anything with them once they are created. The only thing they are vulnerable to is their departure, i.e. the end of their life cycle by the garbage collector, but that's a whole different thing. Foe example:
String s = "Tanish";
s + "is a good boy";
This will do nothing. String s is still Tanish. To make the second line of code happen, you will have to assign the operation to some variable, like this:
s = s + "is a good boy";
And, make no mistake! I said strings are immutable, and here I am reassigning s with some new string. But, it's a NEW string. The original string Tanish is still there, somewhere in the pool of strings. Think of it like this: the string that you are creating is immutable. Tanish is immutable, but s is a reference variable. It can refer to anything in the course of its life. So, Tanish and Tanish is a good boy are 2 separate strings, but s now refers to the latter, instead of the former.
StringBuilder is another way of creating strings in Java, and they are mutable. You can change them. So, if Tanish is a StringBuilder, it is vulnerable to every kind of operation (append, insert, delete, etc.).
Now we have the StringBuilder sb, which is same as the String s.
I've used a StringBuilder built-in method, i.e. indexOf(). This methods finds the index of the character I'm looking for. Once I have the index, I delete the character at that index.
Remember, StringBuilder is mutable. And that's the reason I can delete the characters.
indexOf is overloaded to accept 2 arguments (sb.indexOf(substr ,index)). This returns you the position of the first occurrence of string within the sb, starting from index.
In the example string, sb.indexOf(a,1) will give me 4. All I'm trying to say to Java is, "Return me the index of 'a', but start looking for 'a' from index 1'. So, this way I've the very first a at 0, which I don't want to get rid of.
Now all I'm doing inside the for loop is extracting the character at ith position. j represents the position from where to start looking for the extracted character. This is important, so that we don't loose the one character we need. K represents the result of indexOf('a',j), i.e. the first occurrence of a, after index j.
That's pretty much it. Now, as long as we have a character ch lying in the string (indexOf(....) returns -1, if it can't find the specified character (...or the string as i specified before) as a duplicate, we will obtain it's position (k), delete it using deleteCharAt(k) and update j to k. i.e., the next duplicate a (if it exists) will appear after k, where it was last found.
DEMONSTRATION:
In the example I took, let's say we want to get rid of duplicate cs.
So, we will start looking for the first c after the very first c, i.e. index 3.
sb.indexOf("c",3) will give us 7, where a c is lying. so, k = 7. delete it, and then set j to k. Now, j = 7. Basically after deleting the character, the succeeding string shifts to left by 1. So, now at 7th pos we have d, which was at 8 before. Now, k = indexOf("c",7) and repeat the entire cycle. Also, remember that indexOf("c",j) will start looking right from j. which means if c, is found at j, it will return j. That's why when we extracted the first character, we started looking from position 1 after the character's position.
public class Duplicates {
public static void main(String[] args) {
String str="aabbccddeeff";
String[] str1 = str.split("");
ArrayList<String> List = new ArrayList<String>
Arrays.asList(str1);
List<String> newStr = List.stream().distinct().collect(Collectors.toList());
System.out.print(newStr);
}
}

Generating Alphanumeric random string in Java [duplicate]

This question already has answers here:
How to generate a random alpha-numeric string
(46 answers)
Closed 9 years ago.
I am using String Builder from another answer, but I can't use anything but alpha/numeric, no whitespace, punctuation, etc. Can you explain how to limit the character set in this code? Also, how do I insure it is ALWAYS 30 characters long?
Random generator = new Random();
StringBuilder stringBuilder = new StringBuilder();
int Length = 30;
char tempChar ;
for (int i = 0; i < Length; i++){
tempChar = (char) (generator.nextInt(96) + 32);
stringBuilder.append(tempChar);
I have looked at most of the other answers, and can't figure out a solution to this.
Thanks. Don't yell at me if this is a duplicate. Most of the answers don't explain which part of the code controls how long the generated number is or where to adjust the character set.
I also tried stringBuilder.Replace(' ', '1'), which might have worked, but eclipse says there is no method for Replace for StringBuilder.
If you want to control the characterset and length take for example
public static String randomString(char[] characterSet, int length) {
Random random = new SecureRandom();
char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
// picks a random index out of character set > random character
int randomCharIndex = random.nextInt(characterSet.length);
result[i] = characterSet[randomCharIndex];
}
return new String(result);
}
and combine with
char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
to specify the characterset.
It's not based on StringBuilder since you know the length and don't need all the overhead.
It allocates a char[] array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.
more example use here: http://ideone.com/xvIZcd
Here's what I use:
public static String randomStringOfLength(int length) {
StringBuffer buffer = new StringBuffer();
while (buffer.length() < length) {
buffer.append(uuidString());
}
//this part controls the length of the returned string
return buffer.substring(0, length);
}
private static String uuidString() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
You may try this:
//piece
int i = 0;
while(i < length){
char temp =(char) (generator.nextInt(92)+32);
if(Character.isLetterOrDigit(temp))
{
stringBuilder.append(temp);
++i;
}
}
System.out.println(stringBuilder);
Should achieve your goal

Java: String - add character n-times [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 4 years ago.
Is there a simple way to add a character or another String n-times to an existing String?
I couldn’t find anything in String, Stringbuilder, etc.
Apache commons-lang3 has StringUtils.repeat(String, int), with this one you can do (for simplicity, not with StringBuilder):
String original;
original = original + StringUtils.repeat("x", n);
Since it is open source, you can read how it is written. There is a minor optimalization for small n-s if I remember correctly, but most of the time it uses StringBuilder.
In case of Java 8 you can do:
int n = 4;
String existing = "...";
String result = existing + String.join("", Collections.nCopies(n, "*"));
Output:
...****
In Java 8 the String.join method was added. But Collections.nCopies is even in Java 5.
You are able to do this using Java 8 stream APIs. The following code creates the string "cccc" from "c":
String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));
For the case of repeating a single character (not a String), you could use Arrays.fill:
String original = "original ";
char c = 'c';
int number = 9;
char[] repeat = new char[number];
Arrays.fill(repeat, c);
original += new String(repeat);
Use this:
String input = "original";
String newStr = "new"; //new string to be added
int n = 10 // no of times we want to add
input = input + new String(new char[n]).replace("\0", newStr);
You can use Guava's Strings.repeat method:
String existingString = ...
existingString += Strings.repeat("foo", n);
for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());
Its better to use StringBuilder instead of String because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.
In addition to the answers above, you should initialize the StringBuilder with an appropriate capacity, especially that you already know it. For example:
int capacity = existingString.length() + n * appendableString.length();
StringBuilder builder = new StringBuilder(capacity);
public String appendNewStringToExisting(String exisitingString, String newString, int number) {
StringBuilder builder = new StringBuilder(exisitingString);
for(int iDx = 0; iDx < number; iDx++){
builder.append(newString);
}
return builder.toString();
}
String toAdd = "toAdd";
StringBuilder s = new StringBuilder();
for(int count = 0; count < MAX; count++) {
s.append(toAdd);
}
String output = s.toString();
Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).
Something like:
StringBuilder b = new StringBuilder(existing_string);
for(int i = 0; i<n; i++){
b.append("other_string");
}
return b.toString();
Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.
How I did it:
final int numberOfSpaces = 22;
final char[] spaceArray = new char[numberOfSpaces];
Arrays.fill(spaces, ' ');
Now add it to your StringBuilder
stringBuilder.append(spaceArray);
or String
final String spaces = String.valueOf(spaceArray);
To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.
public static String repeat(char what, int howmany) {
char[] chars = new char[howmany];
Arrays.fill(chars, what);
return new String(chars);
}
and
public static String repeatSB(char what, int howmany) {
StringBuilder out = new StringBuilder(howmany);
for (int i = 0; i < howmany; i++)
out.append(what);
return out.toString();
}
using
public static void main(String... args) {
String res;
long time;
for (int j = 0; j < 1000; j++) {
res = repeat(' ', 100000);
res = repeatSB(' ', 100000);
}
time = System.nanoTime();
res = repeat(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeat: " + time);
time = System.nanoTime();
res = repeatSB(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeatSB: " + time);
}
(note the loop in main function is to kick in JIT)
The results are as follows:
elapsed repeat: 65899
elapsed repeatSB: 305171
It is a huge difference
Here is a simple way..
for(int i=0;i<n;i++)
{
yourString = yourString + "what you want to append continiously";
}

Categories