将char []转换为uint16(unsigned short)会产生错误的数字

时间:2012-05-04 21:39:02

标签: c++

我在将char数组转换为unsigned short(UInt16)时遇到问题。我的转换技术似乎是错误的...... 这是代码:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int _tmain(int argc, _TCHAR* argv[])
{
    // Symbols 0x1210 :
    char test[2];
    test[0] = 0x12;
    test[1] = 0x10;

    unsigned short n;
    memcpy(&n, test, sizeof(unsigned short));

    int i=0, arrToInt=0;
    for(i=1;i>=0;i--)
        arrToInt =(arrToInt<<8) | test[i];

    /*
    Now are:

    n = 4114
    arrToInt = 4114

    But! -> 0x1210 == 4624
    */

    return 0;
}

有没有办法(不)反转char数组?

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

for(i=0;i<=1;i++)
    arrToInt =(arrToInt<<8) | test[i];
相关问题