[英]Java long conversion into bytes
我正在嘗試將 long 轉換為字節數組以通過 BLE 消息發送出去。 我嘗試了幾種不同的方法,但未能成功將數據從 long 轉換為字節。 我讀的時間很長,然后我想轉換成一個字節,但保持數字如下所示:
// 例如 long -> 1620903871 long tsLong = System.currentTimeMillis()/1000;
byte[] outgoingbytes = new byte[10];
// this is the outcome of the data conversion and this how the data needs to presented in the bytes
outgoingbytes[0] = 1;
outgoingbytes[1] = 6;
outgoingbytes[2] = 2;
outgoingbytes[3] = 0;
outgoingbytes[4] = 9;
outgoingbytes[5] = 0;
outgoingbytes[6] = 3;
outgoingbytes[7] = 8;
outgoingbytes[8] = 7;
outgoingbytes[1] = 1;
目前,當我將其轉換為 ASCII 時,不能只獲得原始數字。 任何想法如何長成字節?
看一下 Java 的 DataInput 和 DataOutput 接口及其實現:
數據輸入流:
public final long readLong() throws IOException {
readFully(readBuffer, 0, 8);
return (((long)readBuffer[0] << 56) +
((long)(readBuffer[1] & 255) << 48) +
((long)(readBuffer[2] & 255) << 40) +
((long)(readBuffer[3] & 255) << 32) +
((long)(readBuffer[4] & 255) << 24) +
((readBuffer[5] & 255) << 16) +
((readBuffer[6] & 255) << 8) +
((readBuffer[7] & 255) << 0));
}
數據輸出流:
/**
* Writes a <code>long</code> to the underlying output stream as eight
* bytes, high byte first. In no exception is thrown, the counter
* <code>written</code> is incremented by <code>8</code>.
*
* @param v a <code>long</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public final void writeLong(long v) throws IOException {
writeBuffer[0] = (byte)(v >>> 56);
writeBuffer[1] = (byte)(v >>> 48);
writeBuffer[2] = (byte)(v >>> 40);
writeBuffer[3] = (byte)(v >>> 32);
writeBuffer[4] = (byte)(v >>> 24);
writeBuffer[5] = (byte)(v >>> 16);
writeBuffer[6] = (byte)(v >>> 8);
writeBuffer[7] = (byte)(v >>> 0);
out.write(writeBuffer, 0, 8);
incCount(8);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.