我一直在尝试将经常操作的数据存储到一个大的无符号字符数组中(因为 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/