英文:
Getting Date Time in Unix Time as Byte Array which size is 8 bytes with Java
问题
我知道我可以通过4个字节来获取它,就像这样:
int unixTime = (int)(System.currentTimeMillis() / 1000);
byte[] productionDate = new byte[]{
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
但是是否有一种使用移位来获取8个字节的方法呢?
英文:
I know I can get it in 4 bytes like so:
int unixTime = (int)(System.currentTimeMillis() / 1000);
byte[] productionDate = new byte[]{
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
but is there a way to get it in 8 bytes using shifts?
答案1
得分: 4
当然,只需将其解读为有符号的long
。
long unixTime = System.currentTimeMillis() / 1000L;
byte[] bytes = new byte[] {
(byte) (unixTime >> 56),
(byte) (unixTime >> 48),
(byte) (unixTime >> 40),
(byte) (unixTime >> 32),
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
或者,使用 NIO 的 ByteBuffer:
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES)
.putLong(unixTime);
byte[] bytes = buffer.array();
英文:
Sure, just read as a signed long
.
long unixTime = System.currentTimeMillis() / 1000L;
byte[] bytes = new byte[] {
(byte) (unixTime >> 56),
(byte) (unixTime >> 48),
(byte) (unixTime >> 40),
(byte) (unixTime >> 32),
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
Alternatively, using NIO ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES)
.putLong(unixTime);
byte[] bytes = buffer.array();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论