微软公司宣布不再支持你正在使用的 IE浏览器,这会严重影响浏览网页,请使用微软最新的Edge浏览器
您好, 登录| 注册|

C#转C++(数组复制、char转16位无符号整数)

  • 03-28 11:19
  • 米修儿

    LV.0
  • 1087

    浏览

  • 0

    回复

  • 0

    获赞

  • 数组复制:

    C#实现:

    Copy(Array, Int32, Array, Int32, Int32)

    复制 Array 中的一系列元素(从指定的源索引开始),并将它们粘贴到另一 Array 中(从指定的目标索引开始)。 长度和索引指定为 32 位整数。

    c++实现:

    1.字符数组

    使用strcpy

    2.int,float,double等数组

    使用memcpy,如复制一个长度为5 的 float数组,则代码示例如下

    int len = 5;
    
    float a[len] = {1.0 ,1.1, 1.2, 1.3, 1.4};
    
    float b[len];
    
    memset(b, a, len*sizeof(float));
    
    memcpy(b, a, len * sizeof(float));

    注意,第三个参数不是指数组个数,而是指要复制的数据的总字节数长度

    字节数组(C++中unsigned char)转16位整数

    C#实现:

    [System.CLSCompliant(false)]
    public static ushort ToUInt16 (byte[] value, int startIndex);

    参数

    value Byte[]

    包含要转换的两个字节的字节数组。

    startIndex Int32

    value 内的起始位置。

    返回UInt16

    由两个字节构成、从 startIndex 开始的 16 位无符号整数。

        byte[] byteArray = {
                15, 0, 0, 255, 3, 16, 39, 255, 255, 127 };
    
            BitConverter.ToUInt16( byteArray, 1 );
            BitConverter.ToUInt16( byteArray, 0 );
            BitConverter.ToUInt16( byteArray, 3 );
            BitConverter.ToUInt16( byteArray, 5 );
            BitConverter.ToUInt16( byteArray, 8 );
            BitConverter.ToUInt16( byteArray, 7 );
    
    输出:
    index   array elements    ushort
    -----   --------------    ------
        1            00-00         0
        0            0F-00        15
        3            FF-03      1023
        5            10-27     10000
        8            FF-7F     32767
        7            FF-FF     65535

    C++中无符号字节数组转无符号16位整数实现:

    #include <iostream>
    
    using namespace std;
    int main()
    {
    	unsigned char ch[4] = { 0xAA,0x11,0x02,0x04 };    //-----》使用uchar
    	printf("%d  %d\n", *ch, *(ch + 1));
    	printf("%x  %x\n", *ch, *(ch + 1));
    	printf("uint8_t:%d  %d\n", *(uint8_t*)ch, *(uint8_t*)(ch + 1));//十进制
    	printf("uint8_t:%x  %x\n", *(uint8_t*)ch, *(uint8_t*)(ch + 1));//十六进制
    	printf("uint16_t:%d  %d\n", *(uint16_t*)ch, *(uint16_t*)(ch + 1));//十进制
    	printf("uint16_t:%d  %d\n", *(uint16_t*)(ch+2), *(uint16_t*)(ch + 3));//十进制
    	printf("uint16_t:%x  %x\n", *(uint16_t*)ch, *(uint16_t*)(ch + 1));//十六进制
    
    	system("pause");
    	return 0;
    }

    输出:

    同是电子工程师,请一定不要吝啬你的赞!

    0人已赞

    编辑 举报

    LV.1

    4284573

    2718077

    23

    821817

    说说你的看法

  • LV.

    @

    编辑

    删除

    举报

    #该内容仅管理员可见#

    #回复内容已被删除#

    #该内容正在审核#

    回复:

    取消
    发送
  • 现在还没有回复呢,说说你的想法

    现在还没有回复呢,说说你的想法

    全部回复(0)

    现在还没有回复呢,说说你的想法

  • 回复

  • 收藏

  • 点赞

  • 举报有害信息

  • 已超出发布时间24小时,无法编辑与删除
    关于我们 联系方法 广告服务 会议服务 电子星球APP 网站地图 不良信息举报 热线:400-003-2006
    © 2002-2023 Netbroad(网博互动)公司版权所有 津ICP备 11006234号-2 联网备案号:12010402000747 增值电信业务经营许可证:津B2-20120058