English 中文(简体)
Mimic C++ in java structure and written to byte
原标题:Mimic C++ in java structure and writing to byte[]

我将一些C++的编码推到ava瓦,在我的具体情况下,我就是向一个星号撰写数据,以便提交档案。 C++中定义的第一部分是一个由护堤和3只管组成的结构。 第二个部分是数据的主要部分,即在将数据发送到产出流之前,仅对附端进行对应。

我的问题是: 什么是将头等值写给主人的最简单方式? 我知道,我可以在那里拿出1个价值,然后抵消具体数量的 by,并在必要时重复,但这是这样做的最佳方式吗?

此外,我如何管理逐条调整? C++代码似乎使用默认数值(4-byte?)来统一。

Thanks, Jason

最佳回答

You might find it easier to use ByteBuffer, which is probably the nicest way in Java to organize byte-by-byte output.

虽然我不知道C++是如何调整其产出的——但是,在关键方面,你只能人工推进。

问题回答

采用一个数据OutputStream,总结一个BteArrayOutputStream

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()
DataOutputStream stream = new DataOutputStream(byteArrayOutputStream);

try {
    stream.writeInt(i);
    stream.writeShort(s0);
    stream.writeShort(s1);
    stream.writeShort(s2);
    stream.flush();
} catch (IOException e) {
    // this can t happen, but you still require a try catch block
}

byte[] array = byteArrayOutputStream.toByteArray();

If your code might be parsing a similar byte array with unsigned integers then you re going to have a bit of headache. That is, you will have to check for negative numbers and deal with them appropriately. eg.

int unsignedIntAsSignedInt = inStream.readInt();
long realData;
if (unsignedIntAsSignedInt < 0) {
    realData = ((long) unsignedIntAsSignedInt) - (((long)Integer.MIN_VALUE) * 2);
} else {
    realData = unsignedIntAsSignedInt;
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签