交换C中无符号长(8字节)内的字节

时间:2017-09-09 20:04:17

标签: c byte

unsigned long swap_bytes(unsigned long n) {
    unsigned char bytes[8];
    unsigned long temp;
    bytes[0] = (n >> ??) & 0xff;
    bytes[1] = (n >> ??) & 0xff; 
    // ...
}

我对如何移动8字节unsigned long感到很困惑  例如:0x12345678deadbeef0x34127856addeefbe。我开始这个,但我现在卡住了。请帮忙。

3 个答案:

答案 0 :(得分:5)

您可以使用&二进制AND来掩盖两个版本中的每个其他字节 然后以相反的方向移动两个屏蔽值,并使用|二进制OR组合它们。

n =   ((n & 0xff00ff00ff00ff00ull)>>8ull)
    | ((n & 0x00ff00ff00ff00ffull)<<8ull);

如果它是4byte(与unsigned long相比我认为是unsigned long long,但这是特定于实现的),那么代码是

n =   ((n & 0xff00ff00ul)>>8ul)
    | ((n & 0x00ff00fful)<<8ul);

答案 1 :(得分:0)

你可以试试这个

void swap(char *ptr, int i, int j)
{
    char temp=*(ptr+i);
    *(ptr+i)=*(ptr+j);
    *(ptr+j)=temp;
}
int main()
{
    //unsigned long n = 0x12345678deadbeef;
    uint64_t n = 0x12345678deadbeef;

    char *ptr=(char *)&n;

    swap(ptr, 0, 1);
    swap(ptr, 2, 3);
    swap(ptr, 4, 5);
    swap(ptr, 6, 7);
}

n的地址被转换为char指针并存储在ptr中。

ptr+i将提供i的{​​{1}}字节的地址,其值(即n)由*(ptr+i)函数适当修改。

修改:如果您不确定swap()的大小是否为8字节,则可以使用unsigned long中的uint64_t

答案 2 :(得分:0)

普遍&amp;可怕

public class DrawRect : MonoBehaviour {
    [SerializeField]
    public RectTransform rect;

    private Vector3 startPos;
    private Vector3 endPos;

    void Start () {
        rect.gameObject.SetActive (false);
    }

    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            RaycastHit hit;

            if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, Mathf.Infinity)) {
                startPos = hit.point;
            }
        }

        if (Input.GetMouseButtonUp(0)) {
            rect.gameObject.SetActive (false);
        }

        if (Input.GetMouseButton (0)) {
            if (!rect.gameObject.activeInHierarchy) {
                rect.gameObject.SetActive (true);
            }
            endPos = Input.mousePosition;

            Vector3 squareStart = Camera.main.WorldToScreenPoint (startPos);
            squareStart.z = 0f;

            Vector3 center = (squareStart + endPos / 2f);

            rect.position = center;

            float sizeX = Mathf.Abs (squareStart.x - endPos.x);
            float sizeY = Mathf.Abs (squareStart.y - endPos.y);

            rect.sizeDelta = new Vector2 (sizeX, sizeY);
        }
    }
}

用法:

void swapbytes(void *p, size_t size)
{
    uint8_t tmp, *ptr = p;

    for (size_t i = 0; i < (size - 1); i += 2)
    {
        tmp = *(ptr + i);
        *(ptr + i) = *(ptr + i + 1);
        *(ptr + i + 1) = tmp;
    }
}