C 语言 - [就地复制] float* 到 char* 以及相反

发布于 2024-09-16 18:56:00 字数 420 浏览 4 评论 0原文

我想将浮点缓冲区复制到字符(字节)缓冲区中,而不为两个单独的缓冲区分配内存。换句话说,我想使用一个缓冲区并就地复制。 问题是,如果我需要一个浮点缓冲区,那么为了将其复制到 char,那么我将需要一个 char* 指针;如果我从 float* 复制到 float* ,这会很容易,因为我只需为目标和源传递相同的指针。

例如。

void CopyInPlace(float* tar, float* src, int len) {
....
}
CopyInPlace(someBuffer, someBuffer, 2048);

void PackFloatToChar(char* tar, float* src, int len) {

}
????????

我该怎么做?

如果传入同一个指针,memcpy 是否就地复制?

I want to copy a float buffer into a char (byte) buffer without allocating memory for two separate buffers. In another words I want to use one buffer and copy in place.
The Problem is that if I need a float buffer then in order to copy that to a char then I will need a char* pointer; If I were copying from float* to float* it would be easy as I would just pass in the same pointer for the target and the source.

eg.

void CopyInPlace(float* tar, float* src, int len) {
....
}
CopyInPlace(someBuffer, someBuffer, 2048);

void PackFloatToChar(char* tar, float* src, int len) {

}
????????

How would I do this?

Does memcpy copy in place?, if passed in the same pointer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眼角的笑意。 2024-09-23 18:56:00

如果要将 float 指针转换为 char 指针,强制转换就足够了。

float* someBuffer;
...
char* someBuffer2 = (char*)someBuffer;

If you want to convert a float pointer to a char pointer, a cast is sufficient.

float* someBuffer;
...
char* someBuffer2 = (char*)someBuffer;
明月松间行 2024-09-23 18:56:00

你的问题似乎有点混乱。

您是否想简单地将浮点数组解释为字符数组(用于写入文件之类的操作?)。如果是这样,只需投射即可。 C 中的所有指针都可以用 char* 表示。

memcpy 将从一个内存位置复制到另一个内存位置。但请仔细跟踪您的“len”参数是浮点数还是字节数。如果“len”是数组中浮点数的计数,请将其乘以 memcpy 调用中的 sizeof(float)。

Your question seems a bit confused.

Do you want to simply interpret an array of floats as a char array (for something like writing to a file?). If so, simply cast. All pointers in C can be represented by char*'s.

memcpy will copy from one memory location to another. But keep careful track of whether your "len" parameter is the number of floats or number of bytes. If "len" is the count of floats in the array, multiply it by sizeof(float) in the memcpy call.

女中豪杰 2024-09-23 18:56:00

作为已经推荐的强制转换的替代方案,您可能需要考虑使用联合,例如:

union x { 
    float float_val;
    char bytes[sizeof(float)];
};

两种方式都不可能有巨大差异,但您可能会发现一种方式比另一种方式更方便或更具可读性。

As an alternative to the casting that's already been recommended, you might want to consider using a union, something like:

union x { 
    float float_val;
    char bytes[sizeof(float)];
};

There isn't likely to be a huge difference either way, but you may find one more convenient or readable than the other.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文