fork download
  1. import java.nio.charset.StandardCharsets;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6. int cmdId = 0xF105; // cmdID
  7. String[] strValues = { ""};
  8.  
  9. for (String str : strValues) {
  10. StringBuilder stringBuilder = new StringBuilder();
  11. byte[] bytes = constructReplyPkt(cmdId, str);
  12.  
  13. for (byte b : bytes) {
  14. String s = Integer.toHexString(b & 0xFF) + " ";
  15. if (s.length() < 3) {
  16. s = "0" + s;
  17. }
  18. stringBuilder.append(s);
  19. }
  20.  
  21. System.out.println("Packet for str=\"" + str + "\": " + stringBuilder);
  22. }
  23. }
  24.  
  25. protected static byte[] constructReplyPkt(int nCmdId, String sDataContent) {
  26. if (sDataContent == null) {
  27. sDataContent = "";
  28. }
  29. byte[] baDataContent = sDataContent.getBytes(StandardCharsets.US_ASCII);
  30. return constructReplyPkt(nCmdId, baDataContent);
  31. }
  32.  
  33. protected static byte[] constructReplyPkt(int nCmdId, byte[] baDataContent) {
  34. return constructReplyPkt(nCmdId, baDataContent, 1, 1);
  35. }
  36.  
  37. public static final byte PKT_HEAD_BYTE = (byte) 0x27;
  38. public static final byte PKT_DIR_PCtoTV = (byte) 0x01;
  39. public static final byte PKT_TAIL_BYTE = (byte) 0xFB;
  40.  
  41. protected static byte[] constructReplyPkt(int nCmdId, byte[] baDataContent, int nFrameNo, int nTotalFrameCnt) {
  42. int nbaDataContentLen = (baDataContent != null) ? baDataContent.length : 0;
  43. int nPktTotalLen = 9 + nbaDataContentLen;
  44.  
  45. if (nPktTotalLen > 255) {
  46. return null; // 若封包長度超過255則返回null
  47. }
  48.  
  49. byte[] onePkt = new byte[nPktTotalLen];
  50. onePkt[0] = PKT_HEAD_BYTE;
  51. onePkt[1] = PKT_DIR_PCtoTV;
  52. onePkt[2] = (byte) ((nCmdId & 0xFF00) >> 8);
  53. onePkt[3] = (byte) (nCmdId & 0x00FF);
  54. onePkt[4] = (byte) nbaDataContentLen;
  55.  
  56. if (baDataContent != null) {
  57. System.arraycopy(baDataContent, 0, onePkt, 5, nbaDataContentLen);
  58. }
  59.  
  60. onePkt[5 + nbaDataContentLen] = (byte) nFrameNo;
  61. onePkt[6 + nbaDataContentLen] = (byte) nTotalFrameCnt;
  62.  
  63. byte nChksum = 0;
  64. for (int nByteId = 1; nByteId < onePkt.length - 2; nByteId++) {
  65. nChksum ^= onePkt[nByteId];
  66. }
  67.  
  68. onePkt[7 + nbaDataContentLen] = nChksum;
  69. onePkt[8 + nbaDataContentLen] = PKT_TAIL_BYTE;
  70.  
  71. return onePkt;
  72. }
  73. }
  74.  
Success #stdin #stdout 0.15s 57896KB
stdin
Standard input is empty
stdout
Packet for str="": 27 01 f1 05 00 01 01 f5 fb