my hexadecimal string
string s=new String("FF7900002481201132570943440402151302961500080054021E000040FFFFFBFF79000024812011");
i want particular data in string..
my format : 2481201132570943440402151302961500080054021E000040FFFFFBFF790000
it's must starting value in string 24 .
and it's split at end of 62 . values(2481201132570943440402151302961500080054021E000040FFFFFBFF790000=62)
and finally to split the string ?
12 content value in hexadecimal
24 ---> (1)
8120113257 --(5)
094047 ---(3)
040215 ---(3)
13029615 ----- (4)
00 ------- (1)
080054021E -------(5)
000040 ---- (3)
FFFFFBFF -- (4)
79 ---(1)
00 ------(1)
00 ----- (1)
how to solve it in java code?
Thanks
You can parse the String as a series of Strings.
class StringParser {
final StringReader sr;
public StringParser(String text) {
sr = new StringReader(text);
}
public String next(int n) {
char[] chars = new char[n];
sr.read(chars);
return new String(chars);
}
public String nextAsLong(int n) {
return Long.parseInt(next(n));
}
}
StringParser sp = new StringParser("FF7900002481201132570943440402151302961500080054021E000040FFFFFBFF79000024812011");
sp.next(8); // ignored
long first= sp.nextAsLong(2);
long second = sp.nextLong(10);
// etc
You can use
Long.parseLong(string, 16);
Size of content is fixed or floating?
If yes you can use substring and: Long.parseLong("FFFFFBFF", 16);
Related
So I'm creating a scanner to read off of a simple text file:
import java.io.*;
import java.util.Scanner;
public class Weather {
public static void main(String[] args) throws FileNotFoundException {
int a;
File weatherData = new File("C:\\Users\\taddi\\eclipse-workspace\\COS_160_ASSIGNMENT_10\\src\\PortlandWeather1941to2018.txt");
Scanner scnr = new Scanner(weatherData);
scnr.useDelimiter("//");
int totalCount = scnr.nextInt();// this reads the number at the beginning and uses it so I know how many times to run the loop
String throwAway1 = scnr.nextLine();//these statement are used to throw a way the rest of line 1, and all of line 2 and 3
String throwAway2 = scnr.nextLine();
String throwAway3 = scnr.nextLine();
int[] month = new int[totalCount];
int[] day = new int[totalCount];
int[] year = new int[totalCount];
int[] tmax = new int[totalCount];
int[] tmin = new int[totalCount];
for(a = 0; a < totalCount; a ++) {
month[a] = scnr.nextInt();
System.out.println(month[a]);
day[a] = scnr.nextInt();
System.out.println(day[a]);
year[a] = scnr.nextInt();
tmax[a] = scnr.nextInt();
tmin[a] = scnr.nextInt();
}
}
}
The first part of the text file is an integer I'm trying to read. For some reason, it only reads that integer when I comment out the scnr.useDelimiter("//"); line, otherwise I get an InputMismatchException
I'd love to just get rid of all the unnecessary words and slashes in the text file but that wouldn't satisfy the assignment. What's going wrong with the delimiter? How do I read the integer?
Your delimiter is a string, and it will not work in your use case the way you want.
I assume your sample data is like this (ignoring the header lines) ...
01/01/1941 38 25
01/02/1941 32 20
... so you are looking to get each number - the date elements and the tmax/tmin values - so a single delimiter character of '/' would only break up the date.
For example:
final String data =
"01/01/1941 38 25 \n"+
"01/02/1941 32 20 \n";
Scanner scnr = new Scanner(data);
scnr.useDelimiter("/");
while(scnr.hasNext()) {
System.out.println(scnr.next());
}
scnr.close();
outputs the following ...
01
01
1941 38 25
01
02
1941 32 20
showing that it splits on the date d/m/y slashes, but the year and tmax and tmin are bundled together.
Adjusting the scanner to use a Pattern delimiter allows us to split on the slashes and the spaces.
final String data =
"01/01/1941 38 25 \n"+
"01/02/1941 32 20 \n";
Scanner scnr = new Scanner(data);
scnr.useDelimiter(Pattern.compile("[/ ]+"));
while(scnr.hasNext()) {
System.out.println(scnr.next());
}
scnr.close();
}
giving the output I think you want:
01
01
1941
38
25
01
02
1941
32
20
However, note that in my example data I have trailing whitespace on each line and they are thus also returned as empty String tokens. If I was scanning for nextInt() I would get an java.util.InputMismatchException error. Depending on the exact formatting of your input you may need to cater for that.
This question already has answers here:
how to encode and decode emoji in android?
(8 answers)
Closed 2 years ago.
I am making an ASCII Encoder-Decoder. I am encoding the characters into UTF-8. To encode I am using this code:
private String asciiReturn(String inpString){
int codePoint = 0;
StringBuilder str = new StringBuilder();
for (int i = 0; i < inpString.length(); i++){
codePoint = Character.codePointAt(inpString, i);
i += Character.charCount(codePoint) - 1;
str.append(codePoint);
str.append(" ");
}
return str.toString();
}
So by this, I can encode all those emoji characters too.
Like '🤷🏻♂️' for this emoji I am getting "129335 127995 8205 9794 65039". So this is basically the UTF-8 decimal value of the emoji and that's exactly what I want. But my problem is the decoding.
What I want is: (Example)
Input String: "72 117 104 33 129335 127995 8205 9794 65039"
Output String: "Huh!🤷🏻♂️"
Cause:
72 -> 'H'
117 -> 'u'
104 -> 'h'
33 -> '!'
129335 127995 8205 9794 65039 -> '🤷🏻♂️'
Thanks in advance 🙂
Try this.
private String decode(String inpString) {
return Arrays.stream(inpString.split("\\s+"))
.map(s -> Character.toString(Integer.parseInt(s)))
.collect(Collectors.joining());
}
and
String input = "72 117 104 33 129335 127995 8205 9794 65039";
System.out.println(decode(input));
output
Huh!🤷🏻♂️
You can also write your encoding method like this:
static String asciiReturn(String s) {
return s.codePoints()
.mapToObj(Integer::toString)
.collect(Collectors.joining(" "));
}
and
String s = "Huh!🤷🏻♂️";
System.out.println(asciiReturn(s));
output
72 117 104 33 129335 127995 8205 9794 65039
I'm not sure what is causing this exception, and the stack trace isn't being helpful as it states it was caused by an unknown source.
The method below takes two hexadecimal strings, one representing an opcode and one representing an operand, and converts them to binary before concatenating them and adding them to an arraylist. Simple enough. In order to ensure each binary string includes the full 8 bits I'm using a small utility method called hexToBinary, for some reason, when I attempt to use this method to convert my hexadecimal strings it causes the exception.
The opcode and operands, which are taken from the asmLine objects give this input below:
A9 10
90 C6
0A 00
11 FF
38 00
7D FF
81 FF
A1 09
AA 00
20 11
58 00
6C 09
FE 10
All of the above hexadecimal values should be converted to binary. But this is not happening. The strange thing is that when I explicitly state the hexadecimal value to be converted by the utility method, as I do with the line String beginBinary = Utils.hexToBinary("FA"); works completely normally. I just can't understand why this isn't working when I'm using the values pulled from the asmLine objects.
public void constructBinaryOutput()
{
ArrayList<String> binaryOut = new ArrayList<String>();
String beginBinary = Utils.hexToBinary("FA"); //This works normally
String endBinary = Utils.hexToBinary("FF"); //This works normally
String twoByteString = beginBinary.concat(" " + beginBinary);
binaryOut.add(twoByteString);
for(AssemblyLine asmLine : lineObjects)
{
String opcodeHex = asmLine.getOpcodeHEX();
String operandHex = asmLine.getOperandHEX();
System.out.println("Hex opcode/operand: " + opcodeHex + " " + operandHex);
String opcodeBinary = Utils.hexToBinary(opcodeHex); //This causes an exception
String operandBinary = Utils.hexToBinary(operandHex);
System.out.println("Hex opcode " + asmLine.getOpcodeHEX() + " converted into binary " + opcodeBinary);
System.out.println("Hex operand " + asmLine.getOperandHEX() + " converted into binary " + operandBinary);
twoByteString = opcodeBinary.concat(" " + operandBinary);
System.out.println("2 Byte instruction: " + twoByteString);
binaryOut.add(twoByteString);
}
}
Utility method hexToBinary
public static String hexToBinary(String hex)
{
String bin = Integer.toBinaryString(Integer.parseInt(hex,16));
int length = bin.length();
return length == 8 ? bin : "00000000".substring(length - 8) + bin;
}
Just a simple mistake in your util function. It should be:
public static String hexToBinary(String hex) {
String bin = Integer.toBinaryString(Integer.parseInt(hex, 16));
int length = bin.length();
return length == 8 ? bin : "00000000".substring(length) + bin;
}
notice the substring.
HTH,
Gal
So I have a string which is from a text file, essentially the text file is just 5 lines which read:
x=1
y=15
z=128
topx=100
leftx=150
label= this is a test
I am able to get the split to work once which separates via the '=' sign, but when I try to split the string again by \n nothing works, I have tried using "\r?\n", line.Separator etc. but the string value always stays the same, basically the 5 lines without the characters before the = sign. How would I pull out the individual lines to assign variables to?
Here is the code I have, basically the println is to try and see if I can get the first value '1' to list separate from the rest of the lines.
public static void main(String[] a) {
15 draw d = new draw();
16 Read r = new Read();
17 String m = r.doRead("variables.txt");
18
19 String[] ss = new String[5];
20 ss = m.split("\n");
21
22 String[] kv= new String[5];
23 for (int i=0; i<ss.length; i++) {
24 kv = ss[i].split("=");
25 String eol = System.getProperty("line.seperator");
26 String test = kv[1];
27 String[] split = new String[5];
28 split = test.split("\n");
29
30
31
32
33 String first = split[0];
34 //String second = split[1];
35 //String third = split[2];
36 //String fourth = split[3];
37 //String fifth = split[4];
38 System.out.println(first);
39 }
When every line looks like
x=1 y=15 z=128 topx=100 leftx=150 label= this is a test
you should first split at a whitespace to get 5 parts (x=1, y=15, ...) and then at = to get the "key" and "value" part of each part.
check this out:
String s = "x=1\ny=15\nz=128\ntopx=100\nleftx=150\nlabel= this is a test";
String[] ss = s.split("\n");
System.err.println( Arrays.asList(ss[0].split("=")) );
First time here. I'm trying to write a program that takes a string input from the user and encode it using the replaceFirst method. All letters and symbols with the exception of "`" (Grave accent) encode and decode properly.
e.g. When I input
`12
I am supposed to get 28AABB as my encryption, but instead, it gives me BB8AA2
public class CryptoString {
public static void main(String[] args) throws IOException, ArrayIndexOutOfBoundsException {
String input = "";
input = JOptionPane.showInputDialog(null, "Enter the string to be encrypted");
JOptionPane.showMessageDialog(null, "The message " + input + " was encrypted to be "+ encrypt(input));
public static String encrypt (String s){
String encryptThis = s.toLowerCase();
String encryptThistemp = encryptThis;
int encryptThislength = encryptThis.length();
for (int i = 0; i < encryptThislength ; ++i){
String test = encryptThistemp.substring(i, i + 1);
//Took out all code with regard to all cases OTHER than "`" "1" and "2"
//All other cases would have followed the same format, except with a different string replacement argument.
if (test.equals("`")){
encryptThis = encryptThis.replaceFirst("`" , "28");
}
else if (test.equals("1")){
encryptThis = encryptThis.replaceFirst("1" , "AA");
}
else if (test.equals("2")){
encryptThis = encryptThis.replaceFirst("2" , "BB");
}
}
}
I've tried putting escape characters in front of the grave accent, however, it is still not encoding it properly.
Take a look at how your program works in each loop iteration:
i=0
encryptThis = '12 (I used ' instead of ` to easier write this post)
and now you replace ' with 28 so it will become 2812
i=1
we read character at position 1 and it is 1 so
we replace 1 with AA making 2812 -> 28AA2
i=2
we read character at position 2, it is 2 so
we replace first 2 with BB making 2812 -> BB8AA2
Try maybe using appendReplacement from Matcher class from java.util.regex package like
public static String encrypt(String s) {
Map<String, String> replacementMap = new HashMap<>();
replacementMap.put("`", "28");
replacementMap.put("1", "AA");
replacementMap.put("2", "BB");
Pattern p = Pattern.compile("[`12]"); //regex that will match ` or 1 or 2
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()){//we found one of `, 1, 2
m.appendReplacement(sb, replacementMap.get(m.group()));
}
m.appendTail(sb);
return sb.toString();
}
encryptThistemp.substring(i, i + 1); The second parameter of substring is length, are you sure you want to be increasing i? because this would mean after the first iteration test would not be 1 character long. This could throw off your other cases which we cannot see!