如何从DWORD RGBA转换为ints? [英] How can I convert from DWORD RGBA to ints?

查看:179
本文介绍了如何从DWORD RGBA转换为ints?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将DWORD(unsigned long)RGBA转换为四个int vars(R,G,B和A)
到目前为止,我有这个函数将4个int转换为DWORD: p>

I have to convert a DWORD (unsigned long) RGBA to four int vars (R, G, B, and A) So far, I have this function to convert the 4 ints to a DWORD:

unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA)
{
	return ((iA << 24) | (iR << 16) | (iG << 8) | iB);
}

如何转换回来?

struct RGBA
{
	int R, G, B, A;
};

RGBA DWORD2RGBA(unsigned long dwColor)
{
	static RGBA tmp;
	//.......conversion process
	return tmp;
}

任何种类的帮助将不胜感激! :)

Any kind of help would be appreciated! :)

感谢

推荐答案

如果我是你, d在打包/解包函数中使用乘法加法运算。类似

If I were you, I'd stick with multiplicative-additive operations in the packing/unpacking functions. Something like this

unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA)
{        
  return ((iA * 256 + iR) * 256 + iG) * 256 + iB;
}

具有对称拆包功能

RGBA DWORD2RGBA(unsigned long dwColor)
{        
  RGBA tmp; /* why did you declare it static??? */

  tmp.B = dwColor % 256; dwColor /= 256;
  tmp.G = dwColor % 256; dwColor /= 256;
  tmp.R = dwColor % 256; dwColor /= 256;
  tmp.A = dwColor % 256; /* dwColor /= 256; */

  return tmp;
}

请注意,整个代码中只有一个魔术常量。

Note that there's only one "magic constant" in the whole code.

当然,如果你有一个以打包数据中的位模式编写的外部规范,那么基于位和移位操作的版本可能更受欢迎。仍

Of course, if you have an external specification that is written in terms of bit patterns in the packed data, a version based on bit and shift opertions might be preferrable. Still

unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA)
{        
  return (((((iA << 8) + iR) << 8) + iG) << 8) + iB;
}

RGBA DWORD2RGBA(unsigned long dwColor)
{        
  RGBA tmp; /* why did you declare it static??? */

  tmp.B = dwColor & 0xFF; dwColor >>= 8;
  tmp.G = dwColor & 0xFF; dwColor >>= 8;
  tmp.R = dwColor & 0xFF; dwColor >>= 8;
  tmp.A = dwColor & 0xFF; /* dwColor >>= 8; */

  return tmp;
}

有更少的魔法常量。

现在你可以将重复动作/子表达式包装在宏或更好的内联函数中,并得到非常紧凑和可读的打包器/解包器。

Now you can wrap the repetivie actions/subexpressions in macros or, better, inline functions and arrive at very compact and readable packer/unpacker.

这篇关于如何从DWORD RGBA转换为ints?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆