Different conversion from BigIntger to byte[] if I use C# and Java - java

If have the following BigInteger:
1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998
If I convert to byte[] using ToByteArray in C# I get a result but if I convert the same BigInteger in Java I get a different result. How can I reach the same result? I need the byte[] since I need to remove the padding and then transform the byte array resulting into a string

As pointed out in the comments, the reason you're seeing different values between the byte[] from the C# BigInteger and the Java BigInteger is that the byte order is reversed: C# is little-endian and Java is big-endian.
(See Java vs. C#: BigInteger hex string yields different result? for more details).
As you can see, the order of the bytes in the array is exactly reversed:
C#
BigInteger bi = BigInteger.Parse("1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998");
byte[] ba = bi.ToByteArray();
for (int i = 0; i < ba.Length; i++) {
Console.Write(ba[i] + " ");
}
// 54 49 48 50 47 52 48 47 49 50 32 111 110 114 111 105 103 32 44 98 117 108 67
// 32 97 116 105 118 69 32 44 101 108 97 117 113 115 97 80 32 101 110 111 105 108
// 103 101 86 32 111 116 110 101 118 69 32 44 52 57 57 49 47 56 48 47 49 50 32 44
// 105 115 115 111 82 32 111 99 114 97 77
Java
BigInteger bi = new BigInteger("1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998");
byte[] ba = bi.toByteArray();
for (int i = 0; i < ba.length; i++) {
System.out.print(ba[i] + " ");
}
// 77 97 114 99 111 32 82 111 115 115 105 44 32 50 49 47 48 56 47 49 57 57 52 44
// 32 69 118 101 110 116 111 32 86 101 103 108 105 111 110 101 32 80 97 115 113 117
// 97 108 101 44 32 69 118 105 116 97 32 67 108 117 98 44 32 103 105 111 114 110 111
// 32 50 49 47 48 52 47 50 48 49 54
If you want a Java byte[] to hold the bytes in the same order as C#, you will need to reverse its contents.
You can just write a simple helper method that reverses the order of the bytes in the array:
public static void reverse(byte[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
byte b = array[i];
array[i] = array[j];
array[j] = b;
}
}
Or if you have access to 3rd-party libraries, you can use org.apache.commons.lang3.ArrayUtils.reverse(byte[]).
That would give you a byte[] in Java holding the bytes in the same order as C#:
Java
BigInteger bi = new BigInteger("1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998");
byte[] ba = bi.toByteArray();
reverse(ba);
for (int i = 0; i < ba.length; i++) {
System.out.print(ba[i] + " ");
}
// 54 49 48 50 47 52 48 47 49 50 32 111 110 114 111 105 103 32 44 98 117 108 67
// 32 97 116 105 118 69 32 44 101 108 97 117 113 115 97 80 32 101 110 111 105 108
// 103 101 86 32 111 116 110 101 118 69 32 44 52 57 57 49 47 56 48 47 49 50 32 44
// 105 115 115 111 82 32 111 99 114 97 77

Related

Finding exit from a maze

I wrote this code for a programming assignment given in a course about graphs on Coursera. enter code here. It passes on the test cases given in the question description but fails on one when submitted I'm new to graphs. Can some one help me find the error in this code?
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Iterator;
public class Reachability {
private static boolean[] visited;
private static int reach(ArrayList<Integer>[] adj, int x, int y) {
if(x == y){
return 1;
}
visited[x] = true;
Iterator itr = adj[x].iterator();
while(itr.hasNext()){
x = (int)itr.next();
if(!visited[x]){
return reach(adj,x,y);
}
}
return 0;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
int x, y;
x = scanner.nextInt();
y = scanner.nextInt();
adj[x - 1].add(y - 1);
adj[y - 1].add(x - 1);
}
int x = scanner.nextInt() - 1;
int y = scanner.nextInt() - 1;
visited = new boolean[n];
System.out.println(reach(adj, x, y));
}
}
Given below is the failed test case.
Failed case #6/16: (Wrong answer)
Input:
100 100
27 96
6 9
81 98
21 94
22 68
76 100
8 50
38 86
71 75
32 93
16 50
71 84
6 72
22 58
7 19
19 76
44 75
24 76
31 35
11 89
42 98
63 92
37 38
20 98
45 91
23 53
37 91
76 93
67 90
12 22
43 52
23 56
67 68
1 21
17 83
63 72
30 32
7 91
50 69
38 44
55 89
15 23
11 72
28 42
22 69
56 79
5 83
55 73
13 72
7 93
20 54
21 55
66 89
2 91
18 88
26 64
11 61
28 59
12 86
42 95
17 82
50 66
66 99
40 71
20 40
5 66
92 95
32 46
7 36
44 94
6 31
19 67
26 57
53 84
10 68
28 74
34 94
25 61
71 88
10 89
28 52
72 79
39 73
11 80
44 79
13 77
30 96
30 53
10 39
1 90
40 91
62 71
44 54
15 17
69 74
13 67
24 69
34 96
21 50
20 91
42 46
Your output:
0
Correct output:
1
The problem is that you do an early return from reach() if y cannot be reached via the first unvisited neighbor of x:
return reach(adj,x,y);
What you want to do instead is:
If y can be reached then return 1.
If y cannot be reached then continue with the next neighbor
That would read:
if (reach(adj, x, y) == 1)
return 1;
Unrelated comment: You may want to use Iterator<Integer> instead of the raw type Integer. This avoids the cast and compiler warnings.

Write and Read binary file

I have a test: Write number from 50000 to 60000 to file with any format, then read this data to original number (file size limit 20kb) and cannot use writeShort() method to write or read. But i cannot read file to original number, my code below:
This is write
DataOutputStream out = new DataOutputStream(new FileOutputStream("D:\\mydata2.txt"));
for (int i = 50000; i <= 60000; i++) {
out.write(i);//write() just write 8-bit
}
out.close();
This is read
DataInputStream in = new DataInputStream(new FileInputStream("D:\\mydata2.txt"));
int i=0;
while (in.available() > 0) {
System.out.print(in.readUnsignedByte()+" ");
}
in.close();
Output like this:
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
255 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 100 101 102 103 104 105 106 107 108 109 110 111 112
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
181 182 183 184 185 186 187 188 189
Here's your clue for the 'hard part'. You must do the rest:
byte[] buf = new byte[2];
// (In loop)
buf[0] = (byte)(n >> 8);
buf[1] = (byte)(n & 0xFF);
This is the correct way to do it:
You do not write short, but you write the bytes of it. And the same logic for read too.
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\New\\mydata2.txt"));
for (int i = 50000; i <= 60000; i++)
{
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort((short) i);
byte[] bytes = dbuf.array();
out.writeByte(bytes[0]);
out.writeByte(bytes[1]);
}
out.flush();
out.close();
DataInputStream in = new DataInputStream(new FileInputStream("C:\\New\\mydata2.txt"));
byte[] buf = new byte[2];
while (in.available() > 0)
{
buf[0] = in.readByte();
buf[1] = in.readByte();
// Since Short keyword cannot be used, we could use the following way to get the numbers:
int num = (0xff & buf[0]) << 8 |
(0xff & buf[1]);
System.out.print(num +" ");
}
in.close();
Check this to understand the last conversion with shift operators.

Using priority queue with File Reader

I want to order numbers between the range of 1-100 with File Reader. It's very weird otput. My code:
import java.io.*;
import java.util.*;
public class Main {
public static String strLine;
public static int order = 1;
public static void main(String[] args) {
Queue<String> queue = new PriorityQueue<String>();
try{
FileReader fr = new FileReader("File.txt");
BufferedReader br = new BufferedReader(fr);
while ((strLine = br.readLine()) != null) {
queue.offer(strLine);
}
br.close();
} catch (IOException e){
System.out.println("File not found");
}
while (!queue.isEmpty()){
System.out.println(order + ".Number: " + queue.poll());
order++;
}
} }
File.txt:
81
56
42
3
49
100
61
76
74
79
6
90
34
93
22
71
72
63
67
18
14
5
91
39
53
86
40
45
60
55
48
62
8
4
80
11
87
47
15
46
97
66
43
58
41
54
33
96
82
44
98
27
85
10
32
95
35
24
7
30
83
9
31
99
25
29
57
36
69
50
28
59
12
37
78
73
70
89
65
51
77
88
20
17
21
94
64
19
26
23
92
52
2
16
68
75
38
1
84
13
output:
1.Number: 1
2.Number: 10
3.Number: 100
4.Number: 11
5.Number: 12
6.Number: 13
7.Number: 14
8.Number: 15
9.Number: 16
10.Number: 17
11.Number: 18
12.Number: 19
13.Number: 2
14.Number: 20
15.Number: 21
16.Number: 22
17.Number: 23
18.Number: 24
19.Number: 25
20.Number: 26
21.Number: 27
22.Number: 28
23.Number: 29
24.Number: 3
25.Number: 30
26.Number: 31
27.Number: 32
28.Number: 33
29.Number: 34
30.Number: 35
31.Number: 36
32.Number: 37
33.Number: 38
34.Number: 39
35.Number: 4
36.Number: 40
37.Number: 41
38.Number: 42
39.Number: 43
40.Number: 44
41.Number: 45
42.Number: 46
43.Number: 47
44.Number: 48
45.Number: 49
46.Number: 5
47.Number: 50
48.Number: 51
49.Number: 52
50.Number: 53
51.Number: 54
52.Number: 55
53.Number: 56
54.Number: 57
55.Number: 58
56.Number: 59
57.Number: 6
58.Number: 60
59.Number: 61
60.Number: 62
61.Number: 63
62.Number: 64
63.Number: 65
64.Number: 66
65.Number: 67
66.Number: 68
67.Number: 69
68.Number: 7
69.Number: 70
70.Number: 71
71.Number: 72
72.Number: 73
73.Number: 74
74.Number: 75
75.Number: 76
76.Number: 77
77.Number: 78
78.Number: 79
79.Number: 8
80.Number: 80
81.Number: 81
82.Number: 82
83.Number: 83
84.Number: 84
85.Number: 85
86.Number: 86
87.Number: 87
88.Number: 88
89.Number: 89
90.Number: 9
91.Number: 90
92.Number: 91
93.Number: 92
94.Number: 93
95.Number: 94
96.Number: 95
97.Number: 96
98.Number: 97
99.Number: 98
100.Number: 99
Process finished with exit code 0
Since it is a queue of Strings it is sorted alphabetically. If you want to keep it as Strings, you can use a custom comparator that converts the Strings to ints and compares those:
// This constructor requires an initial capacity before the comparator
Queue<String> queue = new PriorityQueue<String>(100, new Comparator<String>() {
public int compare(String s1, String s2) {
return Integer.parseInt(s1) - Integer.parseInt(s2);
}
});
Another option is to change the type of the queue to Integer and convert the input:
Queue<Integer> queue = new PriorityQueue<Integer>();
...
while ((strLine = br.readLine()) != null) {
queue.offer(Integer.parseInt(strLine));
}

JOptionPane and Graphs

I would like to know how to give JOptionPane the ability to scroll through a histogram. I managed to get JOptionPane to display my histogram, the only problem is you can't scroll through it. The window stretches to the bottom of the screen and displays only half of the graph.
Note: This only happens when reading large input files that contain 300+ integers between 0 and 130. The program will not recognize anything else.
Input Values:
54
38
42
40
34
51
54
58
61
55
54
42
40
34
51
54
54
54
38
60
42
40
54
54
54
54
54
54
54
54
54
54
54
54
54
54
54
32
28
24
18
9
4
22
31
38
34
41
32
28
24
18
31
38
34
41
32
28
24
18
31
38
34
41
32
28
31
38
35
51
34
41
56
63
59
66
48
46
58
41
56
63
51
59
48
46
58
41
56
63
53
52
58
48
49
58
41
56
63
51
52
59
58
66
63
71
69
70
72
67
66
63
71
74
75
69
73
78
72
67
63
71
74
59
56
69
70
78
72
66
71
74
69
70
78
72
67
63
59
58
57
64
71
72
67
63
59
64
71
73
79
75
78
72
67
63
59
63
71
73
75
78
72
67
63
57
73
77
75
78
72
67
71
73
77
75
78
81
83
87
84
91
92
90
84
76
83
82
89
78
81
83
87
84
91
92
90
84
78
85
82
89
96
91
78
81
83
86
82
91
92
90
84
85
82
89
92
96
91
95
97
98
91
95
97
93
87
85
94
89
92
96
93
96
97
98
98
100
102
95
97
93
87
88
89
93
84
89
92
95
95
95
97
94
91
87
84
80
90
82
80
73
75
70
74
74
75
70
66
63
71
69
70
72
67
66
63
71
55
59
53
58
52
67
63
71
74
59
56
69
70
58
62
56
51
54
49
60
68
62
67
63
59
58
57
64
44
38
42
40
34
51
54
55
54
42
40
34
51
54
54
54
38
42
31
38
34
41
32
28
24
18
31
38
34
41
32
28
24
18
31
38
34
41
32
28
31
28
35
41
34
37
26
23
29
40
45
46
39
31
40
38
29
34
36
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class CoolWeather
{
static JFileChooser selecter;
static Scanner in;
public static void main(String[] args) throws FileNotFoundException
{
//Get Input File
File inputFile;
selecter = new JFileChooser(".");
int status = selecter.showOpenDialog(null);
if(status != JFileChooser.APPROVE_OPTION)
{
JOptionPane.showMessageDialog(null, "Closing Program");
System.exit(0);
}
inputFile = selecter.getSelectedFile();
JOptionPane.showMessageDialog(null, "Opening: " + inputFile.getName());
//Creates Array
int[] temps = readData(inputFile);
//Prints Histogram
showMessage(temps);
}
//The Following Method Creates and Populates An Array With Data
//From The Input File
public static int[] readData(File inputFile) throws FileNotFoundException
{
in = new Scanner(inputFile);
in.useDelimiter("[^0-9/s]+");
int[] temps = new int[131];
int count = 0;
int num;
do
{
num = in.nextInt();
count++;
temps[num]++;
}
while (in.hasNextInt());
JOptionPane.showMessageDialog(null, "The Number Of Entries Read: " + count);
return temps;
}
public static void showMessage(int[] temps)
{
String output = "Temp\tCount\tVisual";
// for each array element, output a bar in histogram
for ( int counter = 0; counter < temps.length; counter++ )
{
if (temps[counter] > 0)
{
output += "\n" + counter + "\t" + temps[ counter ] + "\t";
// print bar of asterisks
for ( int stars = 0; stars < temps[ counter ]; stars++ )
{output += "*";}
}
} // end outer for
JTextArea outputArea = new JTextArea();
outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea, "CoolWeather Histogram", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
This is the JOptionPane I use for UI when handling exceptions, but the principle is the same - JTextArea in JScrollPane
JLabel label = new JLabel(e.getLocalizedMessage() + ":");
label.setFont(getFont().deriveFont(Font.BOLD));
label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(getFont());
textArea.setTabSize(2);
textArea.setText(writer.toString());
SwingUtilities.invokeLater(() -> textArea.setCaretPosition(0));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
scrollPane.setPreferredSize(new Dimension(500, 200));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(label);
panel.add(Box.createVerticalStrut(5));
panel.add(scrollPane);
JOptionPane.showMessageDialog(this, panel, ApplicationInfo.getAppName(), JOptionPane.ERROR_MESSAGE);
JTextArea outputArea = new JTextArea();
outputArea.setText(output);
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
scrollPane.setPreferredSize(new Dimension(500, 200));
JOptionPane.showMessageDialog( null, scrollPane, "CoolWeather Histogram", JOptionPane.INFORMATION_MESSAGE);
System.exit( 0 );

Sorting a matrix by rows in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to get a matrix with rows sorted (descending) like sortrows function in matlab.
A =
95 45 92 41 13 1 84
95 7 73 89 20 74 52
95 7 73 5 19 44 20
95 7 40 35 60 93 67
76 61 93 81 27 46 83
76 79 91 0 19 41 1
to
B =
76 61 93 81 27 46 83
76 79 91 0 19 41 1
95 7 40 35 60 93 67
95 7 73 5 19 44 20
95 7 73 89 20 74 52
95 45 92 41 13 1 84
I am using JAMA which not contains a method like sortrows in matlab.
Which is the fastest way of doing this?
One way to do this is to sort rows from last column to first:
int n = A.length;
for (int c = n - 1; c >= 0; c--) {
// bubble sort
for (int i = 0; i < n; i++) {
for (int j = i; j < n ;j++) {
if (A[i][c] < A[j][c]) {
SWAP(A[i], A[j]); // swap the whole row
}
}
}
}
Time Complexity = O(n * O(sorting algo))
Well if you have a row such as
A = 95 45 92 41 13 1 84 95 7 73 89 20 74 52 95 7 73 5 19 44 20 95 7 40 35 60 93 67 76 61 93 81 27 46 83 76 79 91 0 19 41 1
and you need to sort it to
B = 76 61 93 81 27 46 83 76 79 91 0 19 41 1 95 7 40 35 60 93 67 95 7 73 5 19 44 20 95 7 73 89 20 74 52 95 45 92 41 13 1 84
You could probably write
A = B;
Would this be an acceptable solution? Could you still get an 'A' by doing that?
#codetrolling
I don't know what Jama is, but if your data is stored in a 2 Dimension array then you can use the Column Comparator to sort the data on any column.

Categories