提取个字节的字节数组指定位置 [英] Extract Bytes At specified location from byte array

查看:148
本文介绍了提取个字节的字节数组指定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我是新与Java字节操作。我已经有流动的格式字节数组

hello i am new with byte manipulation in java. i already have byte array with flowing format

1-> datapacketlength (length of name) (first byte)
2-> name  (second byte + datapacket length)
3-> datapacketlength (length of datetime)
4-> current date and time

我怎么能提取名称和当前的日期和时间。我应该使用Arrays.copyOfRange()方法。

MCD

推荐答案

您可以使用的ByteBuffer 并使用您当前的字节数组,然后用随之而来的方法获得下一个浮球,诠释等(如 buffer.getInt buffer.getFloat )。

You can use ByteBuffer and use your current byte array, then use the methods that come with it to get the next float, int etc (such as buffer.getInt and buffer.getFloat).

当您使用包装方法,我相信建立一个新的ByteBuffer你可以得到你的字节数组的一部分。可能性是无止境的:)。为了得到字符串作为你问,你只需要做的是这样的:

You can get a portion of your byte array when you create a new bytebuffer by using the wrap method I believe. The possibilities are endless :). To get strings as you asked, you simply need to do something like:

 byte[] name = new byte[nameLength];
 buffer.get(name);
 nameString = byteRangeToString(name);

在哪里byteRangeToString是返回一个新的字符串重新字节[]的presentation数据传递给它的方法。

where byteRangeToString is a method to return a new string representation of the byte[] data you pass it.

public String byteRangeToString(byte[] data)
{
    try
    {
         return new String(data, "UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
         /* handle accordingly */
    }
}

请参阅: http://developer.android.com/reference/java/ NIO / ByteBuffer.html

使用copyOfRange()如果过度使用可能会遇到你到内存的问题。

Using copyOfRange() may run you into memory issues if used excessively.

这篇关于提取个字节的字节数组指定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆