gpt4 book ai didi

Java 字节数组并将 int 复制到其中

转载 作者:行者123 更新时间:2023-12-01 07:38:20 24 4
gpt4 key购买 nike

在 byte[] 数组中的某个点放置 int 的最佳方法是什么?

假设你有一个字节数组:

byte[] bytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
int someInt = 12355; //0x43, 0x30

我怎样才能像bytes[4] = someInt;那样,现在bytes[4]将等于0x43,bytes[5]将等于0x30?

我习惯于在 C++ 中使用 memcpy,不知道 Java 中的替代方案。

谢谢

最佳答案

如果您还想将 int 的高 0 字节放入 byte[] 中:

void place(int num, byte[] store, int where){
for(int i = 0; i < 4; ++i){
store[where+i] = (byte)(num & 0xFF);
num >>= 8;
}
}

如果您只想将字节存储到最高非零字节:

void place(int num, byte[] store, int where){
while(num != 0){
store[where++] = (byte)(num & 0xFF);
num >>>= 8;
}
}

如果您想要字节大端(最低索引处的最高字节),存储所有四个字节的版本非常简单,另一个稍微困难一点:

void placeBigEndian(int num , byte[] store, int where){
for(int i = 3; i >= 0; --i){
store[where+i] = (byte)(num & 0xFF);
num >>= 8;
}
}

void placeBigEndian(int num, byte[] store, int where){
in mask = 0xFF000000, shift = 24;
while((mask & num) == 0){
mask >>>= 8;
shift -= 8;
}
while(shift > 0){
store[where++] = (byte)((num & mask) >>> shift);
mask >>>= 8;
shift -= 8;
}
}

关于Java 字节数组并将 int 复制到其中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8640193/

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