获取以字节数组表示的Unix时间的日期和时间,大小为8字节,使用Java。

huangapple go评论73阅读模式
英文:

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();

huangapple
  • 本文由 发表于 2020年8月18日 21:53:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63470163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定