Java - Search String For Byte Code - java

I have tried many searches to find a way to search a string for byte code. Here is an example:
String stringThatHasBytes = "hello world hello world[B#9304b1";
If stringThatHasBytes . Does have bytes {
return true or false
}
Is there a method that can search a String for bytes?

You can't do this, in short. Because the printing of a byte changes everytime you print it out. Printing out the bytes doesn't print the actual bytes and it's meaningless if you're looking for exact comparison of bytes.
However, if you only look for any byte printing in the string, just control for [B#s in the string and return true.
String stringThatHasBytes = "hello world hello world[B#9304b1";
if (stringThatHasBytes.indexOf("[B#") >= 0)
return true;
} else return false;
EDIT:
If you need ways of printing bytes in a meaningful way, you should convert the bytes to some meaningful text such as:
public static String convertByteArrayToHexString(byte[] b) {
if (b != null) {
StringBuilder s = new StringBuilder(2 * b.length);
for (int i = 0; i < b.length; ++i) {
final String t = Integer.toHexString(b[i]);
final int l = t.length();
if (l > 2) {
s.append(t.substring(l - 2));
} else {
if (l == 1) {
s.append("0");
}
s.append(t);
}
}
return s.toString();
} else {
return "";
}
}

Would contains be too simple of an answer for you?
boolean hasBytes = str.contains("[B#");
If so let me know I'll show you some good regex! but that should be sufficient.

see if this help
byte[] myByteArray = new byte[5];
myByteArray[0] = 'a';
myByteArray[1] = 'b';
myByteArray[2] = 'c';
myByteArray[3] = 'd';
myByteArray[4] = 'e';
for (byte x : myByteArray)
System.out.println(x);
String myString = "abcde";
System.out.println(myString.equals(new String(myByteArray)));

Related

How do I replace certain characters in a String without using .replace()?

I have to write a programme that encrypts and decrypts hidden messages. My problem is changing the alphabet. Originally I was going to use .replace() method, however, my teacher said we're not allowed to. The only methods we are allowed to do are,
.indexof();
.length();
.substring();
I have no idea how I'm supposed to do this. For example, Apple would be &**$# but how can I do this without .replace();
Below is the idea, can be optimised by yourself :
public String replace(String original, String toBeReplacedStr, String withStr) {
while(true) {
int i = original.indexOf(toBeReplacedStr);
if (i == -1) {
break;
}
original = original.substring(0, i) + withStr + original.substring(i + toBeReplacedStr.length());
}
return original;
}
Or can use the StringBuilder with recursion:
public String replace(String original, String toBeReplacedStr, String withStr) {
int i = original.indexOf(toBeReplacedStr);
if (i < 0) {
return original;
}
StringBuilder sb = new StringBuilder();
String before = original.substring(0, i);
String rawAfter = original.substring(i + toBeReplacedStr.length());
String replacedAfter = replace(rawAfter, toBeReplacedStr, withStr);
return sb.append(before).append(withStr).append(replacedAfter).toString();
}
I suggest you read source code of String.replace(char oldChar, char newChar) to implement your own method.
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) { // comment 1, aims to find
// first index of oldChar. You can use indexOf() to achieve this.
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j]; // comment 2, copy prefix chars
// before the oldChar to buf. You can use subString() to achieve this.
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c; // comment 3,
// replace oldChar with newChar, for other chars, just copy.
// You can use the thought above. I suggest you divide to 3
// methods to do "replace" thing.
i++;
}
return new String(buf, true);
}
}
return this;
}

Put even characters in uppercase, but skipping spaces

I'm trying to convert some text so that every even character becomes uppercase. This works, but if there's a space between words, the code takes the space as a character too. So for example, if the input text is "this is a test", the output is "tHiS Is a tEsT". I want it to ignore the spaces and give "tHiS iS a TeSt" as output.
I now have the following code:
private String result;
private String letter;
private void generateText() {
result = "";
String input = editTextInput.getText().toString();
String lowerCase = input.toLowerCase();
char[] charArray = lowerCase.toCharArray();
for(int i=0;i<charArray.length;i++){
if(String.valueOf(charArray[i]).equals(" ")){
//I don't know what to put here
letter = String.valueOf(charArray[i]);
}else{
if(i%2 == 0){
letter = String.valueOf(charArray[i]);
}else if(i%2 == 1){
letter = String.valueOf(charArray[i]).toUpperCase();
}
}
result += letter ;
}
Log.d("result", result);
}
What do I have to do to skip the spaces?
If it's possible, I would like to skip punctuation marks too, or in general, every character which is not a letter.
Thanks in advance!
(For those who are wondering, I'm making a Spongebob meme text generator app)
If you want to do alternate logic in a loop, you could normally use i % 2 == 0, or (i & 1) == 1, but since the alternation is conditional, you need a variable to store the "state". With simple alternation, a boolean variable is the obvious choice.
Also, continuously converting each char to a String is bad for performance. Just update the char[].
private static String upperEven(String input) {
char[] buf = input.toLowerCase().toCharArray();
boolean upper = false;
for (int i = 0; i < buf.length; i++) {
if (Character.isLetter(buf[i])) {
if (upper)
buf[i] = Character.toUpperCase(buf[i]);
upper = ! upper;
}
}
return new String(buf);
}
Test
System.out.println(upperEven("this IS a TEST"));
Output
tHiS iS a TeSt
Code can be compressed/obscured to this: ;-)
private static String upperEven(String s) {
char[] c = s.toCharArray();
boolean t = false;
for (int i = 0; i < c.length; i++)
if (Character.isLetter(c[i]))
c[i] = ((t = ! t) ? Character.toLowerCase(c[i]) : Character.toUpperCase(c[i]));
return new String(c);
}
This is my solution.
private static void generateText() {
String result = "";
String input = "i am a engineer and student of nit.";
String lowerCase = input.toLowerCase();
Boolean isLower = false;
char[] charArray = lowerCase.toCharArray();
for (int i = 0; i < lowerCase.length(); i++) {
String letter = String.valueOf(charArray[i]);
if (!Character.isLetter(charArray[i])) {
result += letter;
} else {
if(isLower)
letter = letter.toUpperCase();
result += letter;
isLower = !isLower;
}
}
System.out.println(result);
}

Recursively decompressing a String

I have this assignment that needs me to decompress a previously compressed string.
Examples of this would be
i4a --> iaaaa
q3w2ai2b --> qwwwaaibb
3a --> aaa
Here's what I've written so far:
public static String decompress(String compressedText)
{
char c;
char let;
int num;
String done = "";
String toBeDone = "";
String toBeDone2 = "";
if(compressedText.length() <= 1)
{
return compressedText;
}
if (Character.isLetter(compressedText.charAt(0)))
{
done = compressedText.substring(0,1);
toBeDone = compressedText.substring(1);
return done + decompress(toBeDone);
}
else
{
c = compressedText.charAt(0);
num = Character.getNumericValue(c);
let = compressedText.charAt(1);
if (num > 0)
{
num--;
toBeDone = num + Character.toString(let);
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone) + decompress(toBeDone2);
}
else
{
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone2);
}
}
}
My return values are absolutely horrendous.
"ab" yields "babb" somehow.
"a" or any 1 letter string string yields the right result
"2a" yields "aaaaaaaaaaa"
"2a3b" gives me "aaaabbbbbbbbbbbbbbbbbbbbbbbbbbaaabbbbaaaabbbbbbbbbbbbbbbbbbbbbbbbbb"
The only place I can see a mistake in would probably be the last else section, since I wasn't entirely sure on what to do once the number reaches 0 and I have to stop using recursion on the letter after it. Other than that, I can't really see a problem that gives such horrifying outputs.
I reckon something like this would work:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return String.join("", Collections.nCopies(Character.digit(c, 10), compressedText.substring(1, 2))) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
As you can see, the base case is when the compressed String has a length less than or equal to 1 (as you have it in your program).
Then, we check if the first character is a digit. If so, we substitute in the correct amount of characters, and continue with the recursive process until we reach the base case.
If the first character is not a digit, then we simply append it and continue.
Keep in mind that this will only work with numbers from 1 to 9; if you require higher values, let me know!
EDIT 1: If the Collections#nCopies method is too complex, here is an equivalent method:
if (Character.isDigit(c)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Character.digit(c, 10); i++) {
sb.append(compressedText.charAt(1));
}
return sb.toString() + decompress(compressedText.substring(2));
}
EDIT 2: Here is a method that uses a recursive helper-method to repeat a String:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return repeatCharacter(compressedText.charAt(1), Character.digit(c, 10)) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
public static String repeatCharacter(char character, int counter) {
if (counter == 1) {
return Character.toString(character);
}
return character + repeatCharacter(character, counter - 1);
}

char[] return type in code not accepting char[i][] value

public char[] Cache_1(int word_address,int cache_set,int ls,char[] s1)
{
char cache_1[][] = new char[32][4];
char s0[] = new char[32];
InterConnectionNetwork ic = new InterConnectionNetwork();
if(ls == '0') {
if((cache_1[cache_set][0]) == '1') { // Check Valid Bit and transfer content
// if valid bit is high
for(int i=0;i<32;i++) { // Load
s0[i] = cache_1[cache_set][i];
}
} else { // Valid bit low
s0 = ic.determinenode(word_address);
}
return s0;
} else {
if((cache_1[cache_set][0]) == '1') {
for(int i=0;i<32;i++) {
cache_1[cache_set][i] = s0[i];
}
} else
cache_1[cache_set][] = ic.determinenode(word_address); //returns char[]
return (cache_1[cache_set][]); //Problem here
}
}
This is a chunk from the code that I am writing. The problem here is that return type being used is char[] and cache_1[cache_set][] is actually equivalent to single character array, but it is showing an error. Please help me to resolve it.
You should return cache_1[cache_set], not cache_1[cache_set][].
You defined return type as
char[]
which means char array (linear)
and you are returning
cache_1[cache_set][] //should give multiple error and one for not giving index inside the second [?]
if you write this correctly then you are returning an char not char[]
You have to change any one of it.

Hex to Binary String Java

I'm making Encryption now, and on the step 7 which i need to make the HEX String Array(which I have transferred from ASCII into a String Array) into Binary String.
public static void main(String[] args) {
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex numbers that i save from last step
StringBuilder builder = new StringBuilder();
int l = 0;
for(String s : HS) {
builder.append(s);
if (s.length()<=1){
stringHextoBinary[l] = HexToBinary(s.charAt(0));
l++;
System.out.print(HexToBinary(s.charAt(0)) + ",");
}else{
stringHextoBinary[l] = HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1));
l++;
System.out.print(HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1))+",");
}
public static String HexToBinary(char Hex) {
int i = Integer.parseInt(Character.toString(Hex), 16);
String Bin = Integer.toBinaryString(i);
return Bin;
}
}
the if statement can be work with HEX when it has one digit or two digits.
But my problem is here that it prints out
HEX to Binary:
11100,111,111,10111,11101,
its losing 0 in it. :(
so that when i encrypt word "apple" , and decrypt it with same code will come back with word "pppxl" :(
Hope I can get answer ASAP and thanks a lot!
Use this method of the Apache commons StringUtils class
public String leftPad(String str, int size, char padding);
after you've converted your number to 0s and 1s. It might look like
String paddedBin = StringUtils.leftPad(bin, 8, '0');
for example. Not sure how many digits you actually want to pad it to.
Instead of your method taking in chars, you can simply have it take in a string and convert it to binary using:
public static void main(String[] args) {
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex numbers that i save from last step
// creates the string builder, count, and declaration
StringBuilder builder = new StringBuilder();
int l = 0;
string binaryDigits;
// iterates through string array and appends to string that's being built
// (for whatever reason)
for(String s : HS) {
builder.append(s);
binaryDigits = HexToBinary(s);
stringHextoBinary[l++] = binaryDigits;
System.out.print(binaryDigits);
}
// transforms hex string to binary string without losing 0's
public static String HexToBinary(String Hex) {
string toReturn = new BigInteger(Hex, 16).toString(2);
return String.format("%" + (Hex.length*4) + "s", toReturn).replace(' ', '0')
}
You don't need to combine code, as this is all the code that you need to convert a string to a binary string separated by spaces. It will iterate through and change every string to a binary string.
Try this method implementation:
public static String hexCharToBinary(char c) {
final int v;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'A' && c <= 'F') {
v = 10 + c - 'A';
} else if (c >= 'a' && c <= 'f') {
v = 10 + c - 'a';
} else {
throw new IllegalArgumentException();
}
return String.format("%4s", Integer.toBinaryString(v & 0xFF)).replace(' ', '0');
}
Try this out:
stringHextoBinary[l] = new BigInteger(s,16).toString(2);
What this is doing is creating a new Integer with radix of 16 for you hex numbers and then converting that to a string of base 2 (binary). Haven't tested this out since I am not near a computer with a jvm installed but this is just an idea since you seem to need ideas in a hurry.
This should work too:
stringHextoBinary[l] = Integer.toBinaryString(Integer.parseInt(s, 16));

Categories

Resources