简体   繁体   English

在一个字节中存储多个值

[英]Storing multiple values in a byte

I am writing a file to store information about locations on a map, for example where an object would spawn. 我正在写一个文件来存储有关地图上位置的信息,例如,物体将在哪里生成。 I write an byte to the file and within the byte there would be x and y coordinates how would I parse them from the file 我向文件写入一个字节,在该字节内将有x和y坐标,我将如何从文件中解析它们

int typeData = stream.readByte();
int x = typeData >> 2;
int y = typeData & 3;

this is an example of what I'm wanting to achieve. 这是我想要实现的一个例子。 What I am not sure is what would I have to do in the writing process, for example 例如,我不确定在写作过程中该做什么。

outStream.writeByte((x << 2) + (y | 3));

This is an example, this code has not been tested and is likely wrong. 这是一个示例,此代码尚未经过测试,可能有误。

Beware that the byte data type is an 8-bit signed two's complement integer. 注意字节数据类型是8位带符号的二进制补码整数。 Therefore, values are from -128 to +127, included. 因此,值在-128到+127之间。

So you are right when computing the bitwise operations with int variables (x and y), like that: (x << 2) + (y | 3) . 因此,使用int变量(x和y)计算按位运算时,您是正确的,如下所示: (x << 2) + (y | 3) Then you can cast to a byte or let Java automatically cast the result, only at the final step when calling writeByte(). 然后,可以仅在调用writeByte()的最后一步将其强制转换为字节或让Java自动转换结果。

You certainly need more that 8 bits to store your coordinates. 当然,您需要超过8位来存储坐标。 To access to binary data stored in your file, remember that the initial order of a byte buffer is always BIG_ENDIAN when using the standard Java java.nio.ByteBuffer API. 要访问存储在文件中的二进制数据,请记住,使用标准Java java.nio.ByteBuffer API时,字节缓冲区的初始顺序始终为BIG_ENDIAN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM