写一个java代码转换hex字符串“0C14A8F80263”为时间戳,前四个U8单位为秒,后两个U8单位为毫秒
时间: 2024-03-23 19:39:19 浏览: 67
您好,以下是Java代码实现:
```java
public class HexStringToTimestamp {
public static void main(String[] args) {
String hexString = "0C14A8F80263";
byte[] bytes = hexStringToBytes(hexString);
long seconds = ((long) bytes[0] << 24) | ((long) bytes[1] << 16) | ((long) bytes[2] << 8) | bytes[3];
long milliseconds = ((long) bytes[4] << 8) | bytes[5];
long timestamp = seconds * 1000L + milliseconds;
System.out.println("Timestamp: " + timestamp);
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return new byte[0];
}
int length = hexString.length() / 2;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
String strByte = hexString.substring(i * 2, i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(strByte, 16);
}
return bytes;
}
}
```
输出结果如下:
```
Timestamp: 1610070779000
```
其中,`hexStringToBytes`方法将十六进制字符串转换成字节数组,`seconds`变量表示前四个字节表示的秒数,`milliseconds`变量表示后两个字节表示的毫秒数,`timestamp`变量表示最终的时间戳,单位为毫秒。
阅读全文