byte[] demande=new byte[2];
Let's suppose that demande is a data frame which will be send to a socket.
What should be byte[0] and byte[1] if I want send 200. I try to write byte[0]=1 and byte[1]=-56 ( 1*256 - 56)=200 but it don't work. How can I do?
I assume that the number 200 is a decimal value.
As 200 is less than 255 it will fit into one byte because the hexadecimal value of 200 is 0xC8.
So in your case you have two options. Which one is correct depends on the protocol you are using.
Either
byte[] demande = { 0x00, 0xC8 }; // little endian
or
byte[] demande = { 0xC8, 0x00 }; // big endian
Or if you prefer
byte[] demande = new byte[2];
demande[0] = 0x00;
demande[1] = 0xC8;
(little endian)
You can use the ByteBuffer class to create a byte array. If you wanted to convert the integer 200 to a byte array:
ByteBuffer b = ByteBuffer.allocate(2);
b.putInt(0x000000c8);
byte[] result = b.array();
Related
I developing TCP Server Program but I stucked this Server's Protocol
the header is fixed by 0xAA55, header size is 2 Byte
this is the problem I dont know fill in 0xAA55 to byte array
byte[] tmp = new byte[2];
tmp = 0xAA55;
this is not work..
You could wrap tmp with a ByteBuffer and then use ByteBuffer.putShort(short) like
byte[] tmp = new byte[2];
ByteBuffer bb = ByteBuffer.wrap(tmp);
bb.putShort((short) 0xAA55);
System.out.println(Arrays.toString(tmp));
I am making a byte array with predefined size as shown below:
private byte[] newPayload() {
byte[] payload = new byte[100];
Arrays.fill(payload, (byte) 1);
return payload;
}
Now I want to add 8 bytes of current timestamp in the same byte array in front of it.
long time = System.currentTimeMillis();
So first eight bytes will be current timestamp and remaining 92 bytes will be same what I am doing right now.
You can use ByteBuffer to convert long to byte[]. Also you can use System.arraycopy to copy this byte[] to the mail array. Please refer the below code.
ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
buffer.putLong(time);
byte[] timeBytes = buffer.array();
System.arraycopy(timeBytes, 0, payload, 0, timeBytes.length);
I am trying to decrypt a file in Java which was encrypted using the Microsoft CryptoAPI's CryptEncrypt function. I have read that "the encryption block buffer returned is in little-endian byte order (compared to big-endian for Java and .NET above)."
I am using the ByteBuffer and ByteOrder classes in Java and am pretty sure I am doing it wrong because I am getting the same printout with a System.out.println for beforebytes and afterbytes no matter what I try.
byte [] beforebytes = null;
// code to extract bytes from file here
ByteBuffer bb = ByteBuffer.wrap(beforebytes);
bb.order( ByteOrder.LITTLE_ENDIAN); // BIG_ENDIAN doesn't work either?
ByteBuffer slice = bb.slice();
// 'slice' now refers to the same data, but is supposed to be BIG ENDIAN
byte[] afterbytes = new byte[bb.capacity()];
// transfer bytes from this buffer into the given destination array
slice.get(afterbytes, 0, afterbytes.length);
Any help will be greatly appreciated!
Thank you,
Bertrand
I resolved this in C! Java now decrypts correctly what was encrypted by the CryptoAPI.
I started out from the CryptoAPI example at:
http://blogs.msdn.com/b/alejacma/archive/2008/01/28/how-to-generate-key-pairs-encrypt-and-decrypt-data-with-cryptoapi.aspx
Then just before writing the encrypted text to file, I added a block of code from reference
CryptoAPI C++ interop with Java using AES
// reverse bytes of pbData for java
for (unsigned i = 0; i<dwEncryptedLen / 2; i++)
{
BYTE temp = pbData[i];
pbData[i] = pbData[dwEncryptedLen - i - 1];
pbData[dwEncryptedLen - i - 1] = temp;
}
The reference was for AES but I encrypted in RSA. For decryption I used the bouncycastle provider using algorithm "RSA/NONE/PKCS1Padding". To install the bouncycastle provider on Windows 7, follow: http://sce.uhcl.edu/yang/teaching/JDK_JCE_environment_Configuration.htm and reboot!
Hope this will help someone.
The byte order doesn't matter if you get individual bytes (or a byte array) out of the buffer. It only matters if you are getting for example 16-bit short values or 32-bit integer values out of the buffer; in that case, the bytes from the buffer will be swapped appropriately according to the byte order.
For example:
ByteBuffer buf1 = ByteBuffer.wrap(new byte[]{0x01, 0x02, 0x03, 0x04});
buf1.order(ByteOrder.LITTLE_ENDIAN);
int n1 = buf1.getInt();
System.out.println(n1 == 0x04030201);
ByteBuffer buf2 = ByteBuffer.wrap(new byte[]{0x01, 0x02, 0x03, 0x04});
buf2.order(ByteOrder.BIG_ENDIAN);
int n2 = buf2.getInt();
System.out.println(n2 == 0x01020304);
I'm stuck with this. I have to send messages to a server to receive the data that I need.
There is a field after the message's header which is "Length":
The length is the total number of bytes in the payload, which includes
all instances of the Param and Delim fields and excludes the header
and framing characters. The length is a 4-byte unsigned long in
network order (big endian).
The only two examples in the documentation are these:
if payload is
5022=LoginUser|5028=abc|5029=def|5026=1
the length field is
<0x00><0x00><0x00><0x27>
if payload is
5022=Subscribe|4=558|5026=2
the length field is
<0x00><0x00><0x00><0x1B>
I've tried some approaches without success. Any idea on how to handle with this would be very appreciated.
Thank You
final byte[] data = string.getBytes("utf-8");
int length = data.length;
final byte[] bytes = new byte[4];
bytes[3] = (byte) length;
bytes[2] = (byte) length >>> 8;
bytes[1] = (byte) length >>> 16;
bytes[0] = (byte) length >>> 24;
Assuming you have some OutputStream out and String payload:
DataOutputStream dataOut = new DataOutputStream(out);
byte[] payloadBytes = payload.getBytes(java.nio.charset.StandardCharsets.UTF_8);
dataOut.writeInt(payloadBytes.length);
dataOut.write(payloadBytes);
I am trying to decode UTF8 byte by byte with charset decoder. Is this possible?
The following code
public static void main(String[] args) {
Charset cs = Charset.forName("utf8");
CharsetDecoder decoder = cs.newDecoder();
CoderResult res;
byte[] source = new byte[] {(byte)0xc3, (byte)0xa6}; // LATIN SMALL LETTER AE in UTF8
byte[] b = new byte[1];
ByteBuffer bb = ByteBuffer.wrap(b);
char[] c = new char[1];
CharBuffer cb = CharBuffer.wrap(c);
decoder.reset();
b[0] = source[0];
bb.rewind();
cb.rewind();
res = decoder.decode(bb, cb, false);
System.out.println(res);
System.out.println(cb.remaining());
b[0] = source[1];
bb.rewind();
cb.rewind();
res = decoder.decode(bb, cb, false);
System.out.println(res);
System.out.println(cb.remaining());
}
gives the following output.
UNDERFLOW
1
MALFORMED[1]
1
Why?
My theory is that the problem with the way that you are doing it is that in the "underflow" condition, the decoder leaves the unconsumed bytes in the input buffer. At least, that is my reading.
Note this sentence in the javadoc:
"In any case, if this method is to be reinvoked in the same decoding operation then care should be taken to preserve any bytes remaining in the input buffer so that they are available to the next invocation. "
But you are clobbering the (presumably) unread byte.
You should be able to check whether my theory / interpretation is correct by looking at how many bytes remain unconsumed in bb after the first decode(...) call.
If my theory is correct then the answer is that you cannot decode UTF-8 by providing the decoder with byte buffers containing exactly one byte. But you could implement byte-by-byte decoding by starting with a ByteBuffer containing one byte and adding extra bytes until the decoder succeeds in outputing a character. Just make sure that you don't clobber input bytes that haven't been consumed yet.
Note that decoding like this is not efficient. The API design is optimized for decoding a large number of bytes in one go.
As has been said, utf has 1-6 bytes per char. you need to add all bytes to the bytebuffer before you decode try this:
public static void main(String[] args) {
Charset cs = Charset.forName("utf8");
CharsetDecoder decoder = cs.newDecoder();
CoderResult res;
byte[] source = new byte[] {(byte)0xc3, (byte)0xa6}; // LATIN SMALL LETTER AE in UTF8
byte[] b = new byte[2]; //two bytes for this char
ByteBuffer bb = ByteBuffer.wrap(b);
char[] c = new char[1];
CharBuffer cb = CharBuffer.wrap(c);
decoder.reset();
b[0] = source[0];
b[1] = source[1];
bb.rewind();
cb.rewind();
res = decoder.decode(bb, cb, false); //translates 2 bytes to 1 char
System.out.println(cb.remaining()); //prints 0
System.out.println(cb.get(0)); //prints latin ae
}