首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >快速字节复制C++11

快速字节复制C++11
EN

Stack Overflow用户
提问于 2022-03-22 17:14:48
回答 1查看 112关注 0票数 0

我需要转换C#应用程序,它广泛使用字节操作。

举个例子:

代码语言:javascript
复制
    public abstract class BinRecord
    {
        public static int version => 1;

        public virtual int LENGTH => 1 + 7 + 8 + 2 + 1; // 19

        public char type;
        public ulong timestamp; // 7 byte
        public double p;
        public ushort size;
        public char callbackType;

        public virtual void FillBytes(byte[] bytes)
        {
            bytes[0] = (byte)type;

            var t = BitConverter.GetBytes(timestamp);
            Buffer.BlockCopy(t, 0, bytes, 1, 7);

            Buffer.BlockCopy(BitConverter.GetBytes(p), 0, bytes, 8, 8);
            Buffer.BlockCopy(BitConverter.GetBytes(size), 0, bytes, 16, 2);
            bytes[18] = (byte)callbackType;
        }
    }

基本上,BitConverterBuffer.BlockCopy每秒调用1000次。

有几个类继承于上面的基类,它们执行更具体的任务。例如:

代码语言:javascript
复制
    public class SpecRecord : BinRecord
    {
        public override int LENGTH => base.LENGTH + 2;
        public ushort num;

        public SpecRecord() { }
        public SpecRecord(ushort num)
        {
            this.num = num;
        }

        public override void FillBytes(byte[] bytes)
        {
            var idx = base.LENGTH;
            base.FillBytes(bytes);

            Buffer.BlockCopy(BitConverter.GetBytes(num), 0, bytes, idx + 0, 2);
        }
    }

我应该研究C++中的什么方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-22 17:28:05

在我看来,最好的选择是使用C-使用memcpy复制任何对象的字节。

然后,您的上述代码将被重写如下:

代码语言:javascript
复制
void FillBytes(uint8_t* bytes)
{
     bytes[0] = (uint8_t)type;
     memcpy((bytes + 1), &t, sizeof(uint64_t) - 1);
     memcpy((bytes + 8), &p, sizeof(double));
     memcpy((bytes + 16), &size, sizeof(uint16_t));
     bytes[18] = (uint8_t)callbackType;
}

在这里,我使用uint8_tuint16_tuint64_t代替byteushortulong类型。

请记住,时间戳副本不能移植到大端CPU,它将切断最低字节而不是最高字节。解决这个问题需要手动复制每个字节,如下所示:

代码语言:javascript
复制
//Copy a 7 byte timestamp into the buffer.
bytes[1] = (t >> 0) & 0xFF;
bytes[2] = (t >> 8) & 0xFF;
bytes[3] = (t >> 16) & 0xFF;
bytes[4] = (t >> 24) & 0xFF;
bytes[5] = (t >> 32) & 0xFF;
bytes[6] = (t >> 40) & 0xFF;
bytes[7] = (t >> 48) & 0xFF;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71576273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档