create a specific number of bytes from a string - java

I would like to know if there is a way to create a specific number of bytes from a string.
I am trying to unit test some part of my code and it can take an array of bytes or a string.
But the data that I am getting will consist exactly 132 bytes (where each data point is two byte signed integers that uses 2's complement).
The data I am retrieving will consist of multiple data points in the above bytes where each data point is 2bytes.
I am planning to unit test my code. So I would like to create a string and convert to byte array and pass it so that I can cross check my data points again.
Also are there any tools available by which I can send binary data via a com port. I was looking at eltima software serial port.

there is this way which I am doing, but looking for more easy way...
final String MACID = new Character((char) 48).toString();
final String STX = new Character((char) 2).toString();
final String str = MACID + STX;
final byte[] utf8Bytes = str.getBytes("UTF-8");
this would surely just take 2 bytes.

Related

Java how to read from randomaccessfile into string?

I have a randomaccess file that stores name, address, city, state, and zipcode.
They are all a fixed size of bytes in the file (each entry). How would I read from the file into a string for each item like name, street, etc?
I've tried
string name = raf.readUTF();
But I can't control how many bytes it reads will that stop it from working correctly? Or how does readUTF work exactly since no amount of total bytes to read can be supplied in the arguement?
Or is a better approach to do
ENTRY1_SIZE = 32;
raf.read(string1);
raf.skipBytes(ENTRY1_SIZE - string1.size());
raf.read(string2);
and so on like that.
What would be the most efficient way to do this while still using a randomaccessfile?
Basically I want to know how to read N bytes into a string that can be displayed in a textbox later.
Response to the answer below.
I tried your method
long position = 91;
byte[] b = new byte[32];
try{
raf.seek(position);
raf.readFully(b, position, 32);
String name = (b, StandardCharsets.UTF_8);
But this error: The method readFully(byte[], int, int) in the type RandomAccessFile is not applicable for the arguments (byte[], long, int)
What should be supplied for the middle argument? The current file pointer is a long so that wouldn't work either.
Another error: StandardCharsets cannot be resolved or is not a field
The javadoc has your answer. readUTF is meant to be used only for strings that have been previously written to the file using writeUTF. If your file has fixed-length regions, you should use readfully(byte[]) using an appropriately-sized byte array, and then convert the byte array to a string using new String(bytes, StandardCharsets.UTF_8).

How to convert "java.nio.HeapByteBuffer" to String

I have a data structure java.nio.HeapByteBuffer[pos=71098 lim=71102 cap=94870], which I need to convert into Int (in Scala), the conversion might look simple but whatever which I approach , i did not get right conversion. could you please help me?
Here is my code snippet:
val v : ByteBuffer= map.get("company").get
val utf_str = new String(v, java.nio.charset.StandardCharsets.UTF_8)
println (utf_str)
the output is just "R" ??
I can't see how you can even get that to compile, String has constructors that accepts another string or possibly an array, but not a ByteBuffer or any of its parents.
To work with the nio buffer api you first write to a buffer, then do a flip before you read from the buffer, there are lots of good resources online about that. This one for example: http://tutorials.jenkov.com/java-nio/buffers.html
How to read that as a string entirely depends on how the characters are encoded inside the buffer, if they are two bytes per character (as strings are in Java/the JVM) you can convert your buffer to a character buffer by using asCharBuffer.
So, for example:
val byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
byteBuffer.putChar('H').putChar('i').putChar('!')
byteBuffer.flip()
val charBuffer = byteBuffer.asCharBuffer
assert(charBuffer.toString == "Hi!")

Best way to encode minimalistic messages

I need to create a little client/server application that should transfer data like this:
statistic <- command type identifier
15.23.63.12 <- Statistic for this IP address
increase <- the kind of action that should be done with the address's statistic
6 <- Just some other parameters...
So there has to be one string that identifies the type of the command and then there should be some parameters depending on the command type. This parameters are different but always primitive data types. Most probably String, Short, Byte, Integer, and so on...
So there are instruction sets of different primitive data types.
My question is: Is it the best way to wrap the socket's streams in DataInput/OutputStreams and just read/write from them? Or is it better to save the messages into a byte array and then wrap this byte array in a ByteArrayInputStream and wrap the ByteArrayInputStream in a DataInputStream that I can read from? Or should I wrap the byte array in a ByteBuffer?
And if I wanted to encrypt my messages, would I have to save them as a byte array, then decrypt the byte array and then wrap it into some kind of data reader?
You could do this more "efficient" if that's what you're asking.
I would model the command type modifier with bytes, provided that you don't have more than 255 distinct modes:
byte cmd_statistic = 0;
byte cmd_nonstatistic = 1;
Then each ip address could be modeled as 4 bytes, like this:
byte[] ip0 = new byte[]{15, 23, 63, 12};
byte[] ip1 = new byte[]{15, 23, 63, 13};
The action could also be bytes:
byte action_increase = 0;
byte action_decrease = 1;
And if you could model the last parameters as bytes you could get away with just using InputStreams (is) and OutputStreams like this:
// Code for reading, writing is very similar
byte cmd = (byte)is.read();
byte[] ip = new byte[4];
is.read(ip, 0, 4);
byte action = (byte)is.read();
byte extra = (byte)is.read();
This is also easy to keep in a large byte[] and that is easier to use for encryption

how to create a byte from string representation of a byte

i am working on a project(web application with java 2 ee) and i need to send an OutputStream on a COM port, the data type in the OutputStream is byte[], one byte of this data is the address of the destination hardware which i am trying to communicate with .
problem is the address of the hardware has to be provided by the user within a web page. so how can i convert the string representation of a byte into a real byte?
i hope the following code can make the problem more vivid
String data1 = "0xA1";
String data2 = "0xAB";
and i need to put the following line in OutputStream.
byte[] b = new byte[]{0xA1,0xAB};
some say usingorg.apache.commons.codec.binary.Base64 can solve the problem but i don't have any clue .
thank you in advance.
It's easy:
byte b = Integer.decode("0xA1").byteValue();
Link to javadoc.
you can use the below method in order to convert a String to its byte value representation, but you need to send it only the part of the String without the "0x"
public static byte convertStringToByte(String str){
return (byte)Integer.parseInt(str, 16);
}
If you want to have fun in doing it yourself instead of doing it through a function call
do it like below
Get the ASCII value
Divide it by 2 collect the reminder (which will be 1 or 0 )
Finally reverse the whole sequence
For example, for decimal 32 you should get 0100000
If you are initializing the COM port, you can also some sequences (ASCII sequences)
directly instead of binary, check the manual.

how to make a searchable String ID with a byte[] using java and hibernate

i am working on a RFID project, in which i should identify vehicles with their RFID tag.
the RFID Tags contain 14 bytes of data.
my first clue was to convert each byte of the array to string something like this :
public String convertByteToString(byte[] tag)
{
String stringRfid ="";
for(int i=0; i<14; i++)
stringRfid = stringRfid + tag[i];
return stringRfid;
}
i don't know if this is a humble solution or what. some say and i quote it "storing raw byte[] in BLOB - the safest and most storage-effective way."
would you please give me tip what is the fastest and easiest and also efficient way to do this?
I would transform the byte array to a base64-encoded readable string, and store this string in the database. It would only increase the size with a 4/3 ratio (so around 20 bytes instead of 14), and would store readable, indexable and printable ascii strings in the database.
Guava and apache commons-codec both have a free base64 encoder/decoder.

Categories