Anyone know how can I convert a large array of bytes, ex 1000 bytes into an int/long etc in java?
You can use a loop
byte[] bytes =
int[] ints = new int[bytes.length];
for(int i=0;i<bytes.length;i++)
ints[i] = bytes[i];
A 1000 elements might take up to 10 micro-seconds this way.
To convert a byte to an int in Java, you have two options:
byte val = 0xff;
int a = val; // a == -1
int b = (val & 0xff); // b == 0xff
There is no method in the Java library to convert an array from one primitive type to another, you'll have to do it manually.
Thanks PaĆlo. Here's the corrected answer:
public class Main {
public static int[] convert(byte[] in) {
int bytesPerSample = 4;
int[] res = new int[in.length / bytesPerSample];
for (int i = 0; i < res.length; i++) {
int bOffset = i * bytesPerSample;
int intVal = 0;
for (int b = 0; b < bytesPerSample; b++) {
int v = in[bOffset + b];
if (b < bytesPerSample - 1) {
v &= 0xFF;
}
intVal += v << (b * 8);
}
res[i] = intVal;
}
return res;
}
public static byte[] convert(int[] in) {
int bytesPerSample = 4;
byte[] res = new byte[bytesPerSample * in.length];
for (int i = 0; i < in.length; i++) {
int bOffset = i * bytesPerSample;
int intVal = in[i];
for (int b = 0; b < bytesPerSample; b++) {
res[bOffset + b] = (byte) (intVal & 0xFF);
intVal >>= 8;
}
}
return res;
}
public static void main(String[] args) {
int[] in = {33, 1035, 8474};
byte[] b = convert(in);
int[] in2 = convert(b);
System.out.println(Arrays.toString(in2));
}
}
Related
I have a specific problem regarding constructor and parameters.
I used byte[] arrays as parameters for my object constructor. My object class compiles just fine, but the test class has an error which i cannot figure out.
I use the right parameters in the test class, but the compiler says there aren't any arguments in the constructor. It's propably just me not seeing the flaw, but i am pretty despirate over this one.
Thank you in advance!
Compiler-Error:
CubeTest.java:6: error: constructor Cube in class Cube cannot be applied to given types;
Cube test = new Cube();
^
required: byte[],byte[],byte[],byte[],byte[],byte[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
The Cube class:
class Cube{
//declare arrays
private byte[] f;
private byte[] r;
private byte[] u;
private byte[] b;
private byte[] l;
private byte[] d;
//
//
//
//constructor
public Cube(byte[] f, byte[] r, byte[] u, byte[] b, byte[] l, byte[] d){
this.f = new byte[9];
this.r = new byte[9];
this.u = new byte[9];
this.b = new byte[9];
this.l = new byte[9];
this.d = new byte[9];
//fill this.f
for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
this.f[i] = f[n];
}
//fill this.r
for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
this.r[i] = r[n];
}
//fill this.u
for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
this.u[i] = u[n];
}
//fill this.b
for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
this.b[i] = b[n];
}
//fill this.l
for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
this.l[i] = l[n];
}
//fill this.d
for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
this.d[i] = d[n];
}
}
}
The test class:
class CubeTest{
public static void main(String args[]){
//f, r, u, b, l, d
//1, 2, 3, 4, 5, 6
//create such arrays
byte[] f = new byte[9];
byte[] r = new byte[9];
byte[] u = new byte[9];
byte[] b = new byte[9];
byte[] l = new byte[9];
byte[] d = new byte[9];
//fill arrays
for(int i = 0; i < 9; i++){
f[i] = 1;
r[i] = 2;
u[i] = 3;
b[i] = 4;
l[i] = 5;
d[i] = 6;
}
//create Cube named test
Cube test = new Cube(f, r, u, b, l, d);
//
}
}
You have to provide a default constructor too in your class Cube.
When you declare a custom constructor Java compiler doesn't create a default one.
I have the following error in compiler
return ans;
^
required: byte[]
found: int[]
I have this method in which i want to return a type of byte . Can anyone tell me how can i cast ans to make it compatible with me method type
public byte[] element(int m) {
//if (q!= a.length)
// throw new Exception("Array length does not equal k");
int f;
int q;
int[] t;
this.first = f;
this.second = q;
this.data = new int[q];
for (int i = 0; i < t.length; ++i) {
this.data[i] = t[i];
}
// if (!this.IsValid())
// throw new Exception("Bad value from array");
int ans[] = new int[this.second];
int a = this.first;
int b = this.second;
int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m
for (int i = 0; i < this.second; ++i) {
ans[i] = largestV(a, b, x); // largest value v, where v < a and vCb < x
x = x - choose(ans[i], b);
a = ans[i];
b = b - 1;
}
for (int i = 0; i < this.second; ++i) {
ans[i] = (first-1) - ans[i];
return ans;
}
}
Note: i want it to return type of byte not int but i am trying to cast ans but without success .
You have to change int[] ans to Byte[] ans, you are trying to return an int array, but you have to return your byte array
int f;
int q;
int [] t;
this.first = f;
this.second = q;
this.data = new int[q];
for (int i = 0; i < t.length; ++i)
this.data[i] = t[i];
// if (!this.IsValid())
// throw new Exception("Bad value from array");
byte ans []= new byte[this.second];
int a = this.first;
int b = this.second;
int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m
for (int i = 0; i < this.second; ++i) {
ans[i]= largestV(a, b, x); // largest value v, where v < a and vCb < x
x = x - choose(ans[i], b);
a = ans[i];
b = b - 1;
}
for (int i = 0; i < this.second; ++i)
ans[i] = (first-1) - ans[i];
return ans;
}
Dunno why you would wanna to work on int and return a byte. Dat aside, You can create a new byte array of the same size as ans and do this in the last loop
for (int i = 0; i < this.second; ++i)
{
ans[i] = (first-1) - ans[i]);
ans_byte_version[i] = (byte) ((first-1) - ans[i]);
}
return ans_byte_version;
However it'd be better if you tell us what are you trying to do. Why have you declared int when you want byte in the first place.
In 'eightbitfulladder' function,I am trying to complement the sumno which is the result of addition of a positive number and a negative number.I found out the number it is sending in the 'convertobyte' function is different from the sumno computed. This is wierd. Can someone explain me what is happening.
import static java.lang.Math.pow;
public class CAModifiedBoothsMultiplier {
public byte byteArrayTobyte(byte[] b) {
byte value = 0;
for (byte i = 0; i < 8; i++) {
value += (b[i] * (pow(2, i)));
}
return value;
}
public byte[] twosComplement(byte x) {
byte y = (byte) (~x + 1);
byte mask = 1;
mask = (byte) (mask << 7);
byte num[] = new byte[10];
byte i = 0, num1 = 0;
for (i = 0; i < 8; i++) {
if ((y & mask) == 0)
num1 = 0;
else
num1 = 1;
y = (byte) (y << 1);
num[i] = num1;
}
return num;
}
public byte[] saveByte(byte number) {
byte mask = 1;
mask = (byte) (mask << 7);
byte num[] = new byte[10];
byte num1 = 0;
byte i = 0;
for (i = 0; i < 8; i++) {
if ((number & mask) == 0)
num1 = 0;
else
num1 = 1;
number = (byte) (number << 1);
num[i] = num1;
}
return num;
}
public byte[] eightbitFullAdder(byte a, byte b, byte cin) {
byte sum = 0, temp1 = 0, cout = 0;
byte sumno[] = new byte[10];
byte ain[] = saveByte(a);
byte bin[] = new byte[10];
if (cin == 1) {
bin = twosComplement(b);
cin = 0;
} else {
bin = saveByte(b);
}
System.out.print("The number entered is, a :");
for (int i = 0; i < 8; i++) {
System.out.print(ain[i]);
}
System.out.println("\n");
System.out.print("The number entered is, b :");
for (int i = 0; i < 8; i++) {
System.out.print(bin[i]);
}
System.out.println("\n");
for (int i = 7; i >= 0; i--) {
temp1 = (byte) (ain[i] ^ bin[i]);
sum = (byte) (temp1 ^ cin);
sumno[i] = sum;
cout = (byte) ((ain[i] & bin[i]) | (cin & temp1));
if (i != 0)
cin = cout;
}
for (int i = 0; i < 8; i++) {
System.out.print(sumno[i]);
}
System.out.println("\n");
if (sumno[0] == 1) {
byte[] sumnocomp = new byte[10];
byte temp2 = 0;
temp2 = byteArrayTobyte(sumno);
System.out.print(temp2);
sumnocomp = twosComplement(temp2);
return sumnocomp;
} else {
return sumno;
}
}
public static void main(String args[]) {
CAModifiedBoothsMultiplier mbm = new CAModifiedBoothsMultiplier();
byte x = 5;
byte complementedno[];
complementedno = mbm.twosComplement(x);
for (int i = 1; i <= 8; i++)
System.out.print(complementedno[i]);
System.out.println("\n");
byte a = 6, b = 8, cin = 1;
byte fulladder[] = mbm.eightbitFullAdder(a, b, cin);
System.out.print("The sum of numbers entered is :");
for (int i = 0; i < 8; i++) {
System.out.print(fulladder[i]);
}
System.out.println("\n");
}
}
I'm trying to implement memoized version of recursive rod cutting algorithm. Here is my code (I implemented it from Cormen's pseudo code)
public class simpleMemoized {
//finds maximum of two given integers
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static int MemoizedCutRod(int price, int lenght) {
int[] r = new int[lenght + 1];
for (int i = 1; i <= lenght; i++) {
r[i] = 0;
}
return MemoizedCutRodAux(price, lenght, r);
}
public static int MemoizedCutRodAux(int price, int lenght, int[] r) {
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
if (r[lenght] >= 0) {
return r[lenght];
}
if (lenght == 0) {
return 0;
}
int q = 0;
for (int i = 1; i <= lenght; i++) {
q = max(q, priceTable[i] + MemoizedCutRodAux(price, lenght, r));
r[lenght] = q;
}
return q;
}
All outputs of this code are 0. But non memorized version of this code is working. What is the problem with it? Here is the working code:
public class Simple {
//finds maximum of two given integers
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static int cormenCutRod(int price, int lenght) {
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
if (lenght == 0) {
return 0;
}
int q = 0;
for (int i = 1; i <= lenght; i++) {
q = max(q, priceTable[i] + cormenCutRod(price, lenght - i));
}
return q;
}
This should work.
static int cutRodM(int lenght)
{
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
int[] mem= new int[lenght+1];
mem[0] = 0;
int i, j;
//filling the table bottom up
for (i = 1; i<=lenght; i++)
{
int q = 0;
for (j = 1; j <= i; j++)
q = max(q, priceTable[j] + mem[i-j]);
mem[i] = q;
}
return mem[lenght];
}
Ideone link: http://ideone.com/OWgrAZ
I am writing a program for a class to first encrypt a string with a predetermined key. That part is done. Next part is where i have a problem or not a problem per se. its a question of redundancy. After this I am supposed to do a KPA on the string and the encrypted string to find the key.
Which is working but i am using like 15 nested for loops for the brute force. Is there another way to do this? without doing it recursively!
static String Key = null;
public static void main(String[] args) {
long startTime = System.nanoTime();
long startTime1 = System.currentTimeMillis();
int cntr = 0;
String key = "AAAAAAAAAAADDDAM";
String plaintext = "Secretfoemotherd";
StringBuilder cipher = new StringBuilder();
StringBuilder brutus = new StringBuilder();
byte[] ciphertext = encrypt(byteT(key), byteT(plaintext));
for (int i = 0; i < ciphertext.length; i++) {
cipher.append(ciphertext[i]);
}
while (true) {
char[] nkey = new char[16];
for (int i1 = 65; i1 < 122; i1++) {
nkey[0] = (char) i1;
for (int i2 = 65; i2 < 122; i2++) {
nkey[1] = (char) i2;
for (int i3 = 65; i3 < 122; i3++) {
nkey[2] = (char) i3;
for (int i4 = 65; i4 < 122; i4++) {
nkey[3] = (char) i4;
for (int i5 = 65; i5 < 122; i5++) {
nkey[4] = (char) i5;
for (int i6 = 65; i6 < 122; i6++) {
nkey[5] = (char) i6;
for (int i7 = 65; i7 < 122; i7++) {
nkey[6] = (char) i7;
for (int i8 = 65; i8 < 122; i8++) {
nkey[7] = (char) i8;
for (int i9 = 65; i9 < 122; i9++) {
nkey[8] = (char) i9;
for (int i10 = 65; i10 < 122; i10++) {
nkey[9] = (char) i10;
for (int i11 = 65; i11 < 122; i11++) {
nkey[10] = (char) i11;
for (int i12 = 65; i12 < 122; i12++) {
nkey[11] = (char) i12;
for (int i13 = 65; i13 < 122; i13++) {
nkey[12] = (char) i13;
for (int i14 = 65; i14 < 122; i14++) {
nkey[13] = (char) i14;
for (int i15 = 65; i15 < 122; i15++) {
nkey[14] = (char) i15;
for (int i16 = 65; i16 < 122; i16++) {
nkey[15] = (char) i16;
cntr++;
byte[] brutusCipher = Crack(
byteC(nkey),
byteT(plaintext));
for (int k = 0; k < brutusCipher.length; k++) {
brutus.append(brutusCipher[k]);
}
if (brutus
.toString()
.equals(cipher
.toString())) {
System.out
.println("found it");
System.out
.println("Key: "
+ Key);
System.out
.println("Brutus: "
+ brutus);
System.out
.println("i ran: "
+ cntr
+ "times");
long endTime = System
.nanoTime();
System.out
.println("time:"
+ (endTime - startTime)
+ " ns");
long endTime1 = System
.currentTimeMillis();
System.out
.println("Took "
+ (endTime1 - startTime1)
+ " ms");
return;
}
brutus.setLength(0);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
public static byte[] byteT(String s) {
return s.getBytes();
}
public static byte[] byteC(char[] s) {
StringBuilder temp = new StringBuilder();
for (int i = 0; i < s.length; i++) {
temp.append(s[i]);
}
Key = temp.toString();
return temp.toString().getBytes();
}
public static byte[] encrypt(byte[] key, byte[] plaintext) {
byte[] d = new byte[key.length];
System.out.println(key.length);
for (int i = 0; i < key.length; i++) {
d[i] = (byte) (key[i] ^ plaintext[i]);
}
return d;
}
public static byte[] Crack(byte[] key, byte[] plaintext) {
byte[] n = new byte[key.length];
for (int i = 0; i < key.length; i++) {
n[i] = (byte) (key[i] ^ plaintext[i]);
}
return n;
}
}
Here is my suggestion on how you can improve your code:
char[] nkey = new char[16];
for (int i =0 ;i<16;++i) {
nkey[i] = 65;
}
while (true) {
//... do the stuff you do in the inner of the cycle
int index = 15;
nkey[index]++;
while (index >= 0 && nkey[index] >= 122) {
nkey[index] = 65;
index--;
if (index < 0) {
break;
}
nkey[index]++;
}
}
You can imagine what I do as representing what you iterate upon as a number in base 122-65 and adding one to it.
You could create a class like this (not tested):
class IncrementableCharArray {
private final char[] array;
IncrementableCharArray(int size) {
array = new char[size];
Arrays.fill(array, 'A');
}
boolean increment() {
//here logic to increment the array
int index = 0;
while(index < array.length && array[index] == 'z') index++;
if (index == array.length) return false;
array[index]++;
return true;
}
char[] get() { return array; }
}
The performance won't be better but it will be a little bit more readable. And you can use it like this:
IncrementableCharArray array = new IncrementableCharArray(16);
while(array.increment()) {
char[] nkey = array.get();
//your test here
}