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

标签 c++ arrays byte

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

相关文章:

c# - 将 2 个连续字节转换为一个 int 值提高 C# 中的速度

c++ - 理解 C++ 中的迭代器类

jquery 匹配 : how to find whether a keyword exists in an array?

python - 体系结构如何影响 numpy 数组操作性能?

c++ - 数组的平均分数

java - 如何从 javafx imageView 获取 byte[]?

javascript - 计算 ImageData 对象的大小(以字节为单位)

c++ - 创建指针时没有调用构造函数吗?

python - 如何在python中获取垃圾值

c++ - OpenCV - 如何计算照片中的物体?