gpt4 book ai didi

c++ - 编辑存储在字节数组中的数据

转载 作者:行者123 更新时间:2023-11-28 06:40:00 25 4
gpt4 key购买 nike

我一直在尝试将经常操作的数据存储到一个大的无符号字符数组中(因为 C++ 没有字节类型)。所以,如果我将一个 float 存储到 char 数组中,它将占用 4 个无符号字符。很简单,除了现在如果我想编辑数组中的数据,我需要同时访问所有 4 个元素,据我所知这是不可能的。那么,有没有一种方法可以在不求助于 memcpy() 的情况下将 4 个无符号字符编辑为我想要的浮点值?

例子:

#include <iostream>
#include <string.h>
#include <stdint.h>

using namespace std;

struct testEntity {

float density;
uint16_t xLoc, yLoc;
uint16_t xVel, yVel;
uint16_t xForce, yForce;
uint16_t mass;
uint8_t UId;
uint8_t damage;
uint8_t damageMultiplier;
uint8_t health;
uint8_t damageTaken;
};


int main()
{

testEntity goblin { 1.0, 4, 5, 5, 0, 0, 0, 10, 1, 2, 1, 10, 0 };
testEntity goblin2;
unsigned char datastream[24];
unsigned char* dataPointer = datastream;

memcpy(&datastream, &goblin, sizeof(testEntity));


//I know that datastream[0..3] contains information on goblin.density
//How would I edit goblin.density without memcpy into another testEntity structure?

memcpy(&goblin2, &datastream, sizeof(testEntity));

return 0;
}

最佳答案

这是我做的:

#include <iostream>
#include <string.h>
#include <stdint.h>

using namespace std;

struct testEntity {

float density;
uint16_t xLoc, yLoc;
uint16_t xVel, yVel;
uint16_t xForce, yForce;
uint16_t mass;
uint8_t UId;
uint8_t damage;
uint8_t damageMultiplier;
uint8_t health;
uint8_t damageTaken;
};


int main()
{

testEntity goblin = { 1.0, 4, 5, 5, 0, 0, 0, 10, 1, 2, 1, 10, 0 };
testEntity goblin2;
unsigned char datastream[24];
unsigned char* dataPointer = datastream;
testEntity *goblinP;

memcpy(datastream, &goblin, sizeof(testEntity));


goblinP = (testEntity *) datastream;

cout << goblinP->density << endl;

return 0;
}

关于c++ - 编辑存储在字节数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149235/

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