Display 0 value in hex file - java

I am working on a hex file and display its content but if the value had "0". It did not appear when i print it out.
for example
0 0 0 b7 7a 7a e5 db 40 2 0 c0 0 0 9 18 16 0 e3 1 40 0 0 3f 20 f0 1 5 0 0 0 0 0 0 41 bc 7a e5 db 40 2 0 c0 1 0 9 18 16 0 e3 1 40 0 0 3f 20 f0 1 5 0 0 0 0 0 0 53 3f 7b e5 db 40 2 0 c0 3 0 9 2 19 24 3d 0 22 68 1 db 9
Code
String filename = "C:\\tm09888.123";
FileInputStream in = null;
int readHexFile = 0;
char hexToChar = ' ';
String[] bytes = new String[10];
try
{
in = new FileInputStream(filename);
while((readHexFile = in.read()) != -1)
{
if (Integer.toHexString(readHexFile).equals("f0"))
{
System.out.print("\n\n\n");
}
System.out.print(Integer.toHexString(readHexFile) + " ");
}
}
catch (IOException ex)
{
Logger.getLogger(NARSSTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
When I printed out the file the "0"s did not appear and values such as "c0" became "c".
How I do i rewrite the code to display the "0"s?

Integer.toHexString doesn't guarantee returning a two-digit result.
If you want it to always be two digits, you could use String.format instead:
System.out.print(String.format("%02x ", readHexFile));

When display it on the screen "0" values did not appear and value like "c0" become only "c"
I suspect it's more likely that "0c" becomes just "c". I'd expect "c0" to be fine.
The problem is that you're using Integer.toHexString which will only use as many digits as it needs to. You could manually fix this by writing:
if (readHexFile < 0x10) {
System.out.print("0");
}
Alternatively, just use:
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
...
System.out.print(HEX_DIGITS[readHexFile >> 4]);
System.out.print(HEX_DIGITS[readHexFile % 15]);
System.out.print(" ");
Or even more simply:
System.out.printf("%02x ", readHexFile);
Also note that there's no need to convert to a hex string to compare with 0xf0. You can use:
if (readHexFile == 0xf0) {
System.out.print("\n\n\n");
}

I cannot say what the problem is with the code, but it seems things would be much clearer if you used Scanner
Scanner sc = new Scanner(new File(fileName));
while(sc.hasNext()) {
String s = sc.next();
System.out.println(s);
}

Related

What are the bytes between the strings in Mifare NFC? [duplicate]

This question already has answers here:
Reading Mifare Classic returns strange characters
(2 answers)
Closed 4 years ago.
When I'm reading a Mifare classic 4k card from block to block and convert the bytes to hexadecimal and then to UTF8/ASCII I get weird characters that probably control bytes and not actual text.
Since I'm just converting the whole block directly to UTF, what should I instead do to utilize those bits in between?
Below are the readings I get and to the left the expected translated value.
If you convert the hex yourself you'll see there are strange characters between the words.
c5 42 4e 49 44 00 07 4f 4f 4f 4f 4f 4f 00 4b 42 "Åbnid" "OOOOOO" "KB"
44 44 44 20 44 44 44 44 44 00 82 4d 00 c9 31 39 "DDD DDDDD" "M" "19"
39 34 34 33 34 32 00 d0 4e 4f 39 36 36 36 35 31 "944342" "NO966651"
00000000000070f78800000000000000
30 32 32 20 20 41 53 00 d3 54 4f 54 41 4c 20 4b "022" "AS" "Total k"
4f 4e 54 52 4f 4f 4f 20 41 53 20 00 c9 30 32 38 "ONTROOO AS" "028"
37 30 34 33 33 00 c9 32 30 32 31 30 32 31 31 00 "70433" "20210211"
00000000000070f78800000000000000
How can I implement a method that takes in either a string of hex or array of bytes[] and only returns the words by comma seperation?
You can read by address, probably, you only require to read by data address.
Data Address start from 0 to 63 for Mifare Classic card, 16 sectors with 4 blocks (=1024 bytes)). But Address 0 always store UID or Manufacturer ID. So, start reading from Address 1, Address 2...Address 63. Let me break down for you,
Sector 0: Address 0 , Address 1, Address 2, Address 3
UID/ManufacturerID, Data , Data ,Sector Trail (KeyA,AccessKey,KeyB)
Sector 1: Address 4, Address 5, Address 6, Address 7
Data , Data , Data , Sector Trail
...
Sector 63 ...
So Sector Trail = 00000000000070f78800000000000000
KeyA = 000000000000
AccessKey = 70f78800
KeyB = 000000000000
So every sector, you skip the last address if you don't set read and write protection.So Try this.And Change accordingly, this could be sufficient to read
// final data
String data="";
// read sector 1 and 2
for(int sector = 1; sector < 3, sector++){
// auth sector
auth = mfc.authenticateSectorWithKeyA(sector, bytekey3);
if(auth) {
// read blocks from sector
data += convertHexToString(readBlockData(sector)).trim();
}
}
// read block
private String readBlockData(int sector) {
String blockvalues = "";
// Read all blocks in sector
for (int block = 0; (block < mfc.getBlockCountInSector(sector)); ++block) {
// Get block number for sector + block
int blockIndex = (mfc.sectorToBlock(sector) + block);
try {
// Create a string of bits from block data and fix endianness
// http://en.wikipedia.org/wiki/Endianness
if (block < 3) {
// Read block data from block index
byte[] data = mfc.readBlock(blockIndex);
if (!(sector == 0 && block == 0)) {
String temp = ByteArrayToHexString(data);
blockvalues += temp;
Log.i(TAG, "Block " + blockIndex + " : " + temp);
rawData += ("Block " + blockIndex + " : " + temp + "\n");
}
}
} catch (IOException e) {
Log.e(TAG, "Exception occurred " + e.getLocalizedMessage());
}
}
return blockvalues.trim();
}
public String convertHexToString(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for (int i = 0; i < hex.length() - 1; i += 2) {
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char) decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString().trim();
}
private String ByteArrayToHexString(byte[] inarray) {
int i, j, in;
String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
"B", "C", "D", "E", "F"};
String out = "";
for (j = 0; j < inarray.length; ++j) {
in = inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
out += hex[i];
i = in & 0x0f;
out += hex[i];
}
return out;
}
last part will be string manipulation. so basically, replay all the double quote with space and use String[]yourdata = data.split("\s+"); and you will get your data. Some of the code I borrow from this link

Changing output into 4x4 matrices

So I'm working on a method in Java that basically takes a random string of letters then goes through the method and changes the string into parity bits, which is basically converting each character to its numeric value in binary.
This is what I have:
public class ShiftData {
//this is the method that where Logic is implemented..
static String shiftRows(String text) {
//character array to store given String elements into an array..
char[] chs = text.toCharArray();
StringBuffer samBuffer = new StringBuffer();
//loop through the length of the character array..
for (int i = 0; i < chs.length; i++) {
//adding characters to the StringBuffer...
samBuffer.append(Integer.toHexString((int) chs[i]));
// here in the above statement toHexString method pads parity bit and converts to hexadecimal value..
}
return samBuffer.toString();//returning the value
}
}
This is the code that converts the string into 4x4 matrices:
if(text !=null && !text.isEmpty()) {
int len = text.length();
int rem = len %16;
int padChars = 16-rem;
for(int i =0; i < (len+padChars); i++) {
if(i < len) {
System.out.print(text.charAt(i)+ " ");
} else {
System.out.print( "A ");
}
if((i+1) % 4 == 0)
System.out.println();
if((i+1) % 16 == 0)
System.out.println("\n");
}
}
So basically if the input string is: WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO
The output should look like this:
d7 56 cf 47
d4 d8 d1 ca
48 d8 48 55
59 c9 c3 d7
59 4d 47 48
d2 4b d1 d4
50 d7 48 d1
47 4b 59 56
cc 50 59 53
d7 47 cf 50
d4 cf c9 4e
4d c6 cf 50
cf 41 41 41
41 41 41 41
41 41 41 41
41 41 41 41
I just need help combining the codes! I can get them working separately but I cant get the output I need. Please show how you would code this.
Don't use StringBuffer. Use StringBuilder instead.
Your printing loop is writing one letter at a time, separated by 3 spaces (and newlines). Letters in hex consist of two hex digits, as you already show in the desired output, so that won't work.
Your code prints blank lines at the end, which you probably don't want.
Integer.toHexString() will return a single digits if value is 0-15.
static String shiftRows(String text) {
char[] chs = text.toCharArray();
StringBuilder samBuffer = new StringBuilder();
for (int i = 0; i < chs.length; i++)
samBuffer.append(String.format("%02x", (int)chs[i])); // always 2 hex digits, even for 0-15
return samBuffer.toString();
}
public static void main(String[] args) {
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
if (text != null && ! text.isEmpty()) {
int len = (text.length() + 31) / 32 * 32; // round up to next increment of 32 (16 hex pairs)
for (int i = 0; i < len; i += 2) {
if (i != 0 && i % 8 == 0) { // every 4 hex pairs, but not first time
System.out.println();
if (i % 32 == 0) // every 16 hex pairs
System.out.println();
}
if (i < text.length())
System.out.print(text.substring(i, i + 2) + " ");
else
System.out.print("41 ");
}
}
}

How to read first line of ints in a text file, use those numbers, then go to the second line and repeat until the end of the file

This is my main method. I am trying to read the first line of integers (5 4 3 7 8 4 3 1 3 ) from a text file. I want to then run those numbers through the methods i am calling in my main method. I then want to go to the next line in the text file (15 1 60 1 43 24 3), also run these numbers through the methods I am calling and so on until I reach the end of the text file. What is the best way to implement something like this? How I my code now will run through all of the integers in the text file and then run them through the method.
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
try
{
int num;
Scanner reader = new Scanner(new File("numbers.txt"));
while(reader.hasNextInt())
{
num = reader.nextInt();
if(tree.contains(num))
{
tree.remove(num);
}
else
{
tree.add(num);
}
}
reader.close();
tree.preorder(root);
System.out.println();
tree.inorder(root);
System.out.println();
tree.postorder(root);
System.out.println("\nTotal: " + tree.size(root));
System.out.println("Height: " + tree.height(root));
System.out.println("Max: " + tree.getMax(root));
System.out.println("Min: " + tree.getMin(root));
}
catch(IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
This is the text file that I want to use called numbers.txt
5 4 3 7 8 4 3 1 3
15 1 60 1 43 24 3
25 28 71 18 48 35 97
6 41 24 40 85 2 92 72 86 59 7 40
76 19 23 40 84 6 67 41 34 66 79 11 38 5 61 60 64 5
81 8 30 80 88 38 90 55 37 45 70 32 41 26
I would try something more like this:
public static void main(String[] args) throws Exception {
Scanner reader = new Scanner(new File("numbers.txt"));
while (reader.hasNextLine()) {
String[] temp = reader.nextLine().split("\\s+"); // Regex for any and all whitespace used as a delimiter
for (int x = 0; x < temp.length; x++) {
// Iterate through each element in the string array temp
}
// Resume while loop.
}
}

Java: Is it possible to make line break x times inside for loop?

I tried to Google and search StackOverflow my question but I didn't found any answers to this.
I have made an array where both size and values are randomly generated. When the array values have been printed 20 times I would like to make a line break, but without printing the rest values with always new line.
Here is my code:
public static void catArr() {
Random rändöm = new Random();
int size = rändöm.nextInt(100);
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = rändöm.nextInt(100);
}
Arrays.sort(arr);
for (int i = 0; i < size; i++) {
System.out.print(" " + arr[i]);
if (i > 20)
System.out.println(); //How to do this only once?
else if (i > 40)
System.out.println(); //Same here?
}
}
And this is one of the generated outputs:
3 8 10 25 30 31 34 38 46 50 55 59 62 66 67 68 68 68 72 76 76 81
82
83
84
86
91
92
93
94
94
97
I think that one way to solve this is using 2-D array, but I would like to know if there is another way.
Yay thanks to Patric, I got the wanted result:
0 2 3 7 7 9 11 14 14 16 18 19 24 25 26 28 28 30 30 31
31 33 33 34 41 41 41 42 43 44 45 46 51 51 52 53 59 60 61 62
62 62 63 65 65 67 67 68 69 70 74 74 76 78 82 83 84 84 87 88
89 93 93 94 94 94 95
try using
if ( ( i % 20 ) == 0 ){
System.out.println();
}
if i divided by 20 leaves no remainder then print a new line!
Maybe
if (i % 20==0)
can solve your else if problem.
Use (++i % 20) == 0 and remove i++ from loop; pre-increment avoid first unwanted line break.
Literally, this will do what you seem to want:
if (i == 20)
System.out.println();
else if (i == 40)
System.out.println();
But I have a feeling that you actually want to add a newline after the 20th, 40th, 60th and so on.
if (i % 20 == 0)
System.out.println();
And if you want to output exactly one newline at the end, then you need something like this:
for (int i = 0; i < size; i++) {
if (i > 1 && i % 20 == 1) {
System.out.println();
System.out.print(" " + arr[i]);
}
System.out.println();
You may use boolean for your Sys outs.
boolean myBoolean = true;
if(myBoolean){
//print
myBoolean = false; //set boolean to false.
}
On the other hand, in my preferences, I still stick with my integer flagging.
int isTrue = 1;
if(isTrue == 1){
//print
isTrue = 0;
}

Method prints table incorrectly

I was wondering if someone could help me with a small problem I'm having.
I am trying to print out an array of 100 items, every row needs 10 items, after which it starts a new row. I have done this successfully, however, every row in every column displays the same number. For example. My output would be:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
When it should be appearing as something along the lines of:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
Here is the following method I am using to print the table:
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 10; j++) {
// After 10 go to a new line
System.out.printf("%d\t", emirps[i]);
}
System.out.println("");
}
}
If anyone can help me pinpoint where I have goofed I'd greatly appreciate it.
You are printing the same emirps[i] each time through the inner loop. There are a couple of ways around this. Here's one:
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; i += 10) {
for (int j = 0; j < 10; j++) {
// After 10 go to a new line
System.out.printf("%d\t", emirps[i + j]);
}
System.out.println();
}
}
Here's another (not very elegant):
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; ++i) {
System.out.printf("%d\t", emirps[i]);
if (i % 10 == 9) {
System.out.println();
}
}
}
This looks like homework, so instead of giving you the answer, here's a hint:
For the first iteration of the first loop, i = 0. When this is the case, you increment j from 0 to 9. Note that i stays the same throughout. This is when you print your first line.
Once you're through with the second for loop, i increases by 1 to, and now i = 1. Again, you increment j from 0 to 9, and i stays at 1. This is when you print your second line.
This repeats 100 times, as i goes from 0 to 99.
There are 2 ways of approaching this:
Use one for loop, and figure out when to print an end-of-line character.
Use two for loops, each going up to 10. Figure out your index by simple multiplication and addition.
You should try and implement both methods. It'll help you understand loops better.
You are not using the j index anywhere in this code.
Here is how you should print:
System.out.printf("%d\t", emirps[i+j]);
Notice how in the print statement you are now using both the i and j indices.
Also, to get your row offset working correctly, you should be incrementing i by 10 at each step of the loop.
Alternatively, declare emirps as a 2-dimensional array. Then the signature of printTable() would be:
public static void printTable(int[][] emirps)
In that setup, here is how you would print:
System.out.printf("%d\t", emirps[i][j]);
So in the first setup, i+j together index into a 1-D array. In the second setup, i is the row and j is the column, indexing together into a 2-D array. It looks like you're doing a 1-D array but this other example is for your future reference.
Use the modulo operator. Every time your number can be divided by 10 without a remainder, you can make a new line because you have filled up the row. You obtain the remainder using the 'modulo operator' which is the percent (%) sign. It can be used like /, except that rather than the quotient being the result, the remainder of the division operation is the result.
public static void main(String[] args)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++)
{
if (i != 0 && i % 10 == 0)
{
builder.append('\n');
}
builder.append(i + " ");
}
System.out.println(builder.toString());
}
Prints out:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99

Categories