我在使用 android BLE。
需要将特征当前时间写入为 32 位 UNIX 时间戳。之后以秒为单位写入与 UTC 的当前时区偏移量。可能问题在于转换为 32 字节数组,但我不是 100% 确定。
我做到了,但出了点问题。它上升得非常快,最终超过 0x7FFF,FFFF,即它溢出并变为负值,因为时间戳是一个有符号整数。
private byte[] getCurrentUnixTime() {
int unixTime = (int) (System.currentTimeMillis() / 1000L);
byte[] currentDate = Converter.intTo32ByteArray(unixTime);
return currentDate;
}
private byte[] getCurrentTimeOffset() {
TimeZone tz = TimeZone.getDefault();
Date timeNow = new Date();
int offsetFromUtc = tz.getOffset(timeNow.getTime()) / 1000;
byte[] offsetFromUtcByteArray = Converter.intTo32ByteArray(offsetFromUtc);
return offsetFromUtcByteArray;
}
public static byte[] intTo32ByteArray(int number) {
byte[] byteArray = new byte[]{
(byte) (number >> 24),
(byte) (number >> 16),
(byte) (number >> 8),
(byte) number
};
return byteArray;
}
最佳答案
正在关注 this您正在使用正确的转换。
在Java中
by default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -0x7FFFFFFF and a maximum value of 0x7FFFFFFF-1 oracle.
所以这只是表示的问题(不是数据)。有类似的情况,通过 ARGB 用 int 重复颜色 - 它需要 4*8 位,所以值一次为正值,如果你只想显示它,则为负值。
要显示所需的值,您可以将 byte[] 转换为 long,如 example
关于java - 当前时间作为 32 位 UNIX 时间戳和时间偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103278/