---
title: "计算报文长度，两个字节表示"
author: "virusfu"
date: "2012-05-08T10:07:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2012-11-23T16:03:49Z"
id: 1734071
url: "https://virusfu.iteye.com/blog/1734071"
---

```
方法1
/**
	 * 计算报文长度,两字节报文长度（高位在前）
	 * 
	 * @param len
	 * @return
	 */
	public byte[] getByteMessageLen(int len) {
		byte[] buf = new byte[2];
		//取高8位
		buf[0] = (byte) (len >> 8);
		//取低8
		buf[1] = (byte) (len & 0xff);
		return buf;
	}
方法2
// 获取第一个高位长度
byte first = (byte) (len / 100);
// 获取第二个高位长度
byte second = (byte) (((len % 100) / 10) << 4 | (len % 10));
```

```
//方法1
/** 
  *计算8583表针报文前两字节长度，
  *如：数据0, 115, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0........ 
  *前面的0,115表示报文的长  度，获取报文长度, 两字节16进制报文长度（高位在前），，
  *例如300字节长报文，长度填0x012C ,变为 blen[1] & 0xff 编程无符号整形
*/ 
public static int getMessageLen(byte[] blen) {            
        String hexlen = Integer.toHexString(blen[0]) + Integer.toHexString(blen[1] & 0xff);  
        return Integer.parseInt(hexlen, 16);
   }
方法2
int length = ((buf[pos] & 0x0f) * 100) + (((buf[pos + 1] & 0xf0) >> 4) * 10)+ (buf[pos + 1] & 0x0f);
```