gpt4 book ai didi

java - Android如何将类转换为二进制序列

转载 作者:行者123 更新时间:2023-12-01 04:32:07 26 4
gpt4 key购买 nike

Test test;
Mc_WriteUserData(McHandle, (unsigned char *)&test, sizeof(test));

上面是c++函数的使用方式,我关注的是2ed arg的工作方式,想用java在android中模仿它。以下是我的安卓代码。我在 toBytes() 函数中模仿它。并想像这样使用它:

Test test;
test.toByte();

但它不起作用,任何帮助表示赞赏!

final class Kits{
public static byte[] intToByte(int number){
byte[] bytes = new byte[4];
bytes[0] = (byte) (number & 0xff);
bytes[1] = (byte) ((number & 0xff00) >> 8);
bytes[2] = (byte) ((number & 0xff0000) >> 16);
bytes[3] = (byte) ((number & 0xff000000) >> 24);
return bytes;
}
public static byte[] shortToByte(short number){
byte[] bytes = new byte[2];
bytes[0] = (byte) (number & 0xff);
bytes[1] = (byte) ((number & 0xff00) >> 8);
return bytes;
}
}

class Point{
int x;
int y;
int z;

public byte[] toBytes(){
byte[] bytes = new byte[12];
byte[] byte_4 = new byte[4];
byte_4 = Kits.intToByte(x);
bytes[0] = byte_4[0];
bytes[1] = byte_4[1];
bytes[2] = byte_4[2];
bytes[3] = byte_4[3];
byte_4 = Kits.intToByte(y);
bytes[4] = byte_4[0];
bytes[5] = byte_4[1];
bytes[6] = byte_4[2];
bytes[7] = byte_4[3];
byte_4 = Kits.intToByte(z);
bytes[8] = byte_4[0];
bytes[9] = byte_4[1];
bytes[10] = byte_4[2];
bytes[11] = byte_4[3];
return bytes;
}
}

public class Test {
short u16size; /* total class size */
int u32crc; /* checksum, accumulator total*/
boolean bEnable;
Point pisl[] = new Point[1];
byte u8DevType;

public byte[] toBytes(){
byte[] bytes = new byte[19];
byte[] byte_2 = new byte[2];
byte[] byte_4 = new byte[4];
byte[] byte_12 = new byte[12];
byte_2 = Kits.shortToByte(this.u16size);
bytes[0] = byte_2[0];
bytes[1] = byte_2[1];
byte_4 = Kits.intToByte(this.u32crc);
bytes[2] = byte_4[0];
//more repeat
bytes[6] = this.bEnable ? (byte)1 : (byte)0;
byte_12 = pisl[0].toBytes();
bytes[7] = byte_12[0];
//more repeat
bytes[18] = byte_12[11];
bytes[19] = u8DevType;

return bytes;
}
public static void main(String[] args) {
Test test = new Test();
Mc_WriteUserData(test.toBytes(), 19);
}
}

最佳答案

线路

Test test;

不创建对象。它只创建一个空指针。

您需要使用:

Test test = new Test();

这将创建一个 Test 类的对象,并且 test 将指向该对象。

关于java - Android如何将类转换为二进制序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17872540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com