Reputation: 8180
I working with android BLE.
Need to write to characteristic Current time as 32bit UNIX timestamp. After that write Current timezone offset from UTC in seconds. Probably problem is in coverting to 32 byte array but i am not 100% sure.
I did it but something is wrong. It rises very quickly, and eventually passes 0x7FFF,FFFF, i.e. it overflows and becomes negative as timestamp is a signed integer.
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;
}
Upvotes: 1
Views: 1626
Reputation: 8180
I resolve problem with this int to byte array code conversion
byte[] offsetFromUtcByteArray = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) offsetFromUtc).array();
and
byte[] currentDate = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) unixTime).array();
Upvotes: 0
Reputation: 2417
Following this you are using rigth conversion.
In 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.
So it just a problem with presentation (not data). There's similar case with repesentating colors with int via ARGB - it needs 4*8 bits so value is once positvie, else negative if you want just display that.
To display desirable value you can convert byte[] to long like in this example
Upvotes: 1