How to loop in the file of array byte - java

public byte[][] createShares(byte[] secret, int shares, int threshold, Random rnd)
{
// some code here
}
I have this method and i am going to apply SSS for file of byte array .
byte [] secret is method parameter where i am going to pass as argument each byte of the file and then apply for each byte the SSS algorithm. I have also implemented a java code of how to read the file and then convert it to a byte array. I am stuck of how to implement this SSS algorithm for each byte of files.
I know i need a for loop for that . The point is i want to call to my main method this byte [] secret and assign to it each byte of the file but i am stuck of how to do it .
My method which will read the file and convert it to the array of bit is as below:
public byte[] readFile(File fileName) throws IOException {
InputStream is = new FileInputStream(fileName);
// Get the size of the file
long length = fileName.length();
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
throw new IOException("Could not completely read file " + fileName.getName() + " as it is too long (" + length + " bytes, max supported " + Integer.MAX_VALUE + ")");
}
// Create the byte array to hold the data
byte[] secret = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < secret.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < secret.length) {
throw new IOException("Could not completely read file " + fileName.getName());
}
// Close the input stream and return bytes
is.close();
return secret;
}
Can anyone help me how to loop for each byte of the file and then pass it as the argument to my createshares method ?

I understand you are trying to read bytes from the file and also trying to loop through the byte[].
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
import java.nio.file.Path;
public class SSSAlgorithm {
public static void main(String[] args) {
System.out.println("Reading file");
try {
byte[] secret = readFile();
createShares(secret, 2, 3, 100);
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[][] createShares(byte[] secret, int shares, int threshold, int i)
{
// some code here
for (byte coeff : secret){
System.out.println("Use the byte here " + coeff);
}
return null;
}
public static byte[] readFile() throws IOException {
Path path = Paths.get("/Users/droy/var/crypto.txt");
try {
byte[] secret = Files.readAllBytes(path);
return secret;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
**Output:
Stored secret as 1234
byte array representation: [49, 50, 51, 52, 10]
Use the byte here 49
Use the byte here 50
Use the byte here 51
Use the byte here 52
Use the byte here 10

Related

Stream of short[]

Hi I need to calculate the entropy of order m of a file where m is the number of bit (m <= 16).
So:
H_m(X)=-sum_i=0 to i=2^m-1{(p_i,m)(log_2 (p_i,m))}
So, I thought to create an input stream to read the file and then calculate the probability of each sequence composed by m bit.
For m = 8 it's easy because I consider a byte.
Since that m<=16 I tought to consider as primitive type short, save each short of the file in an array short[] and then manipulate bits using bitwise operators to obtain all the sequences of m bit in the file.
Is this a good idea?
Anyway, I'm not able to create a stream of short. This is what I've done:
public static void main(String[] args) {
readFile(FILE_NAME_INPUT);
}
public static void readFile(String filename) {
short[] buffer = null;
File a_file = new File(filename);
try {
File file = new File(filename);
FileInputStream fis = new FileInputStream(filename);
DataInputStream dis = new DataInputStream(fis);
int length = (int)file.length() / 2;
buffer = new short[length];
int count = 0;
while(dis.available() > 0 && count < length) {
buffer[count] = dis.readShort();
count++;
}
System.out.println("length=" + length);
System.out.println("count=" + count);
for(int i = 0; i < buffer.length; i++) {
System.out.println("buffer[" + i + "]: " + buffer[i]);
}
fis.close();
}
catch(EOFException eof) {
System.out.println("EOFException: " + eof);
}
catch(FileNotFoundException fe) {
System.out.println("FileNotFoundException: " + fe);
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
But I lose a byte and I don't think this is the best way to proced.
This is what I think to do using bitwise operator:
int[] list = new int[l];
foreach n in buffer {
for(int i = 16 - m; i > 0; i-m) {
list.add( (n >> i) & 2^m-1 );
}
}
I'm assuming in this case to use shorts.
If I use bytes, how can I do a cycle like that for m > 8?
That cycle doesn't work because I have to concatenate multiple bytes and each time varying the number of bits to be joined..
Any ideas?
Thanks
I think you just need to have a byte array:
public static void readFile(String filename) {
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
try {
FileInputStream fis = new FileInputStream(filename);
byte b=0;
while((b=fis.read())!=-1) {
outputStream.write(b);
}
byte[] byteData=outputStream.toByteArray();
fis.close();
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe);
}
Then you can manipulate byteData as per your bitwise operations.
--
If you want to work with shorts you can combine bytes read this way
short[] buffer=new short[(int)(byteData.length/2.)+1];
j=0;
for(i=0; i<byteData.length-1; i+=2) {
buffer[j]=(short)((byteData[i]<<8)|byteData[i+1]);
j++;
}
To check for odd bytes do this
if((byteData.length%2)==1) last=(short)((0x00<<8)|byteData[byteData.length-1]]);
last is a short so it could be placed in buffer[buffer.length-1]; I'm not sure if that last position in buffer is available or occupied; I think it is but you need to check j after exiting the loop; if j's value is buffer.length-1 then it is available; otherwise might be some problem.
Then manipulate buffer.
The second approach with working with bytes is more involved. It's a question of its own. So try this above.

How to generate byte arrays for sending data over a network in Java

I am trying to connect to a PostgreSQL server (implementing the wire protocol) but I can't figure out how to dynamically generate message frames of byte arrays. For example, in the following code I'm doing a lot of System.arraycopy calls to push all the generated bytes into a single byte array and it seems like there has to be a better way.
import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
public class Connection {
public void connect(String hostName, int port) {
try {
Socket dbSocket = new Socket(hostName, port);
DataOutputStream dOut = new DataOutputStream(dbSocket.getOutputStream());
byte[] message = buildStartupMessage("sa");
dOut.write(message);
DataInputStream dIn = new DataInputStream(dbSocket.getInputStream());
byte bytes;
while((bytes = dIn.readByte()) != 0) {
System.out.println(bytes);
}
} catch(Exception e) {
System.out.println("Got an exception");
}
}
public byte[] buildStartupMessage(String username) {
// Postgres startup message format:
// 32 bit length
// 32 bit protocol
// string name
// null byte
// string value
// null byte
byte nullbyte = 0;
byte[] valbytes = username.getBytes();
byte[] namebytes = "user".getBytes();
System.out.println("number of bytes for sa is: " + valbytes.length);
int length = 4 + 4 + valbytes.length + namebytes.length + 2;
byte[] lengthbytes = ByteBuffer.allocate(4).putInt(length).array();
byte[] protocolbytes = ByteBuffer.allocate(4).putInt(3).array();
byte[] startupmessage = new byte[length];
int currIndex = 0;
System.arraycopy(lengthbytes, 0, startupmessage, currIndex, lengthbytes.length);
currIndex += lengthbytes.length;
System.arraycopy(protocolbytes, 0, startupmessage, currIndex, protocolbytes.length);
currIndex += protocolbytes.length;
System.arraycopy(namebytes, 0, startupmessage, currIndex, namebytes.length);
currIndex += namebytes.length;
startupmessage[currIndex] = nullbyte;
currIndex++;
System.arraycopy(valbytes, 0, startupmessage, currIndex, valbytes.length);
currIndex += valbytes.length;
startupmessage[currIndex] = nullbyte;
return startupmessage;
}
public static void main(String[] args) {
Connection conn = new Connection();
conn.connect("localhost", 5432);
}
}
Don't. Use the primitives of DataOutputStream to write what you want directly. For example:
dos.writeInt(length); // total length
dos.writeInt(3); // protocol
dos.writeBytes("user");
dos.writeByte(0); // null terminator
dos.writeBytes(username); // username
dos.writeByte(0); // null terminator
... and the converse when reading via the DataInputStream, according to the protocol. Put buffered streams under the data streams to save system calls.
BUT ... The real question here is 'why'? You should certainly be using a PostgresSQL JDBC driver to talk to the server, rather than trying to roll the entire protocol yourself. It's already done for you, by the vendor. Don't do this.
NB When you get an exception, don't print out Got an exception. It is asinine. Print the exception.
Try this.
public byte[] buildStartupMessage(String username) {
ByteBuffer b = ByteBuffer.allocate(100);
b .putInt(0) // length (dummy)
.putInt(3) // protocol
.put("user".getBytes()) // name
.put((byte)0) // null byte
.put(username.getBytes()) // val
.put((byte)0); // null byte
int length = b.position();
b.rewind();
b.putInt(length); // length (actual)
byte[] r = new byte[length];
b.rewind();
b.get(r, 0, length); // copy to byte array
return r;
}

How to decode hex code in an array in java

Need to decode hex code in array when accessed by index.User should enter array index and get decoded hex in array as output.
import java.util.Scanner;
class Find {
static String[] data={ " \\x6C\\x65\\x6E\\x67\\x74\\x68",
"\\x73\\x68\\x69\\x66\\x74"
//....etc upto 850 index
};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int s = in.nextInt();
String decodeinput=data[s];
// need to add some code here
//to decode hex and store to a string decodeoutput to print it
String decodeoutput=......
System.out.println();
}
}
How about using...
String hexString ="some hex string";
byte[] bytes = Hex.decodeHex(hexString .toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Append the following code after getting the value of s from user. Imp: Please use camelCase convention for naming variables as pointed out above. I have just gone ahead and used the same names as you have for your convinience for now.
if (s>= 0 && s < data.length) {
String decodeinput = data[s].trim();
StringBuilder decodeoutput = new StringBuilder();
for (int i = 2; i < decodeinput.length() - 1; i += 4) {
// Extract the hex values in pairs
String temp = decodeinput.substring(i, (i + 2));
// convert hex to decimal equivalent and then convert it to character
decodeoutput.append((char) Integer.parseInt(temp, 16));
}
System.out.println("ASCII equivalent : " + decodeoutput.toString());
}
OR, just complete what you were doing:
/* import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex; //present in commons-codec-1.7.jar
*/
if (s>= 0 && s < data.length) {
String hexString =data[s].trim();
hexString = hexString.replace("\\x", "");
byte[] bytes;
try {
bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println("ASCII equivalent : " + new String(bytes, "UTF-8"));
} catch (DecoderException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

how to do framing for audio signal in java

I want to split my audio file (.wav format) in frames of 32 milliseconds each. Sampling frequency - 16khz, number of channels - 1(mono), pcm signal, sample size = 93638.
After getting the data in the byte format, I am converting the byte array storing the wav file data to double array since I require it to pass it to a method which accepts a double array, I am using the following code can someone tell me how to proceed?
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.ByteBuffer;
public class AudioFiles
{
public static void main(String[] args)
{
String file = "D:/p.wav";
AudioFiles afiles = new AudioFiles();
byte[] data1 = afiles.readAudioFileData(file);
byte[] data2 = afiles.readWAVAudioFileData(file);
System.out.format("data len1: %d\n", data1.length);
System.out.format("data len2: %d\n", data2.length);
/* for(int i=0;i<data2.length;i++)
{
System.out.format("\t"+data2[i]);
}*/
System.out.println();
/* for(int j=0;j<data1.length;j++)
{
System.out.format("\t"+data1[j]);
}*/
System.out.format("diff len: %d\n", data2.length - data1.length);
double[] d = new double[data1.length];
d = toDoubleArray(data1);
for (int j = 0; j < data1.length; j++)
{
System.out.format("\t" + d[j]);
}
daub a = new daub();
a.daubTrans(d);
}
public static double[] toDoubleArray(byte[] byteArray)
{
int times = Double.SIZE / Byte.SIZE;
double[] doubles = new double[byteArray.length / times];
for (int i = 0; i < doubles.length; i++)
{
doubles[i] = ByteBuffer.wrap(byteArray, i * times, times).getDouble();
}
return doubles;
}
public byte[] readAudioFileData(final String filePath)
{
byte[] data = null;
try
{
final ByteArrayOutputStream baout = new ByteArrayOutputStream();
final File file = new File(filePath);
final AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(file);
byte[] buffer = new byte[4096];
int c;
while ((c = audioInputStream.read(buffer, 0, buffer.length)) != -1)
{
baout.write(buffer, 0, c);
}
audioInputStream.close();
baout.close();
data = baout.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}
public byte[] readWAVAudioFileData(final String filePath)
{
byte[] data = null;
try
{
final ByteArrayOutputStream baout = new ByteArrayOutputStream();
final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(filePath));
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, baout);
audioInputStream.close();
baout.close();
data = baout.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}
}
I want to pass the double array d to method performing wavelet transform, in the frames of 32 millisecond since it accepts a double array.
In my previous question I was given a reply that:
At 16kHz sample rate you'll have 16 samples per millisecond. Therefore, each 32ms frame would be 32*16=512 mono samples. Multiply by the number of bytes-per-sample (typically 2 or 4) and that will be the number of bytes per frame.
I want to know whether my frame size changes when I convert my array from byte format to double format or does it remains the same??
My Previous Question.

Parsing a string and converting embedded values to host-byte-order in Java

I have a java client and a C server. I server wants to send a data packet to the client containing some information in a specific order as shown below:
char *buf = NULL;
if(!(buf = malloc(sizeof(char) * pkt_len)))
{
printf("Could not malloc\n");
return -1;
}
memcpy(buf, &pkt_type, 2);
memcpy(buf + 2, &pkt_len, 4);
memcpy(buf + 6, &more_to_come, 1);
memcpy(buf + 7, &fb_id, 8);
memcpy(buf + 15, &match, 4);
memcpy(buf + 19, el->name, name_len);
memcpy(buf + 19 + name_len, "\n\r", 2);
if(send(clientSock, buf, pkt_len, 0) < 0)
{
printf("Can not write to socket %d\n", clientSock);
return -1;
}
Ofcourse I have convereted all the shorts, integers and long integers to network bytes order before writing them to the buffer. The data is received as a string by the Java client. My problem is how to parse this string. For example, I would to know a way to read off the 2 bytes that indicate the pkt length and cast it to a short in host-byte-order. I am aware that Java provides a method to convert a string to an array of bytes. But what do I do after I have obtained the bytes array. Some code to perform this task would be appreciated
You mean something like this?:
char[] charArray = new char[2];
charArray[0] = "a".charAt(0);
charArray[1] = "b".charAt(0);
String string = new String(charArray);
I assume a char is one byte in length here.
You could use a DataInputStream. Depending on your data types, something like the following might get you started. Note the example uses ASCII as the character encoding and doesn't try to be efficient in any way.
package grimbo.test.bytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class BytesTest {
public static void main(String[] args) throws IOException {
// start setup test data
byte[] msgStart = {
/*pkt_type*/0, 1,
/*pkt_len*/0, 0, 0, 1,
/*more_to_come*/1,
/*fb_id*/1, 2, 3, 4, 5, 6, 7, 8,
/*match*/2, 2, 2, 2 };
String name = "John Smith\n\r";
byte[] nameBytes = name.getBytes("ASCII");
byte[] msg = new byte[msgStart.length + nameBytes.length];
System.arraycopy(msgStart, 0, msg, 0, msgStart.length);
System.arraycopy(nameBytes, 0, msg, msgStart.length, nameBytes.length);
// end setup test data
DataInputStream in = new DataInputStream(new ByteArrayInputStream(msg));
new BytesTest().read(in);
}
void read(DataInputStream in) throws IOException {
// assuming pkt_type is an unsigned 2-byte value
int pkt_type = in.readUnsignedShort();
print(pkt_type);
// assuming pkt_len is an unsigned 4-byte value
// Java doesn't have those, so read a signed int and mask to a long
long pkt_len = in.readInt() & 0xFFFFFFFFL;
print(pkt_len);
// assuming vanilla byte is ok for this, but Java bytes are signed, not unsigned
byte more_to_come = in.readByte();
print(more_to_come);
// don't know the format of this, so left as bytes
byte[] fb_id = new byte[8];
in.readFully(fb_id);
print(fb_id);
// don't know the format of this, so left as bytes
byte[] match = new byte[4];
in.readFully(match);
print(match);
char[] nr = { '\n', '\r' };
byte[] name = readUntil(in, nr);
print(name);
System.out.println(">" + new String(name, "ASCII") + "<");
}
private byte[] readUntil(DataInputStream in, /* stop reading when these chars are found */char[] terminate)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int terminateIdx = 0;
int input = -1;
while ((input = in.read()) > -1) {
if (input == terminate[terminateIdx]) {
if (terminateIdx == (terminate.length - 1)) {
// we've found the termination sequence
byte[] buf = baos.toByteArray();
// - terminateIdx because we don't include the termination sequence
byte[] result = new byte[buf.length - terminateIdx];
System.arraycopy(buf, 0, result, 0, result.length);
return result;
}
terminateIdx++;
} else {
// no match, reset count
terminateIdx = 0;
}
baos.write(input);
}
return baos.toByteArray();
}
private void print(long l) {
System.out.println(l);
}
void print(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(bytes[i]);
}
System.out.println();
}
}
And the output is:
1
1
1
1,2,3,4,5,6,7,8
2,2,2,2
74,111,104,110,32,83,109,105,116,104
>John Smith<

Categories

Resources