本文介绍了使用3个字节存储4个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用三个字节来存储四个6位整数(4 * 6 = 3 * 8)
这样的b $ b

11111122 | 22223333 | 33444444

假设输入为int c1,c2,c3,c4,范围0 .. 2 ^ 6 -1

,输出为int o1,o2,o3,范围0 .. 2 ^ 8-1

如何以巧妙的方式做到这一点?


(6位整数代表AZ和0-9范围内的字符)

I need to use three bytes to store four 6-bit integers (4 * 6 = 3 * 8)
like this
11111122|22223333|33444444
Suppose the input is, int c1, c2, c3, c4, range 0 .. 2^6 -1
and the output is int o1,o2,o3, range 0 .. 2^8-1
How to do this in a clever way?

(The 6 bits integers represent characters in range A-Z and 0-9)

推荐答案




未经测试的情况如何:


#define PACKED_INT_RANGE 0x3F / * 6-bit * /


/ * pPacked最好是3个字节或更多

* /

int packInts(int first,int second,int third ,第四,char * pPacked)

{

int failures =!0;


if((first& PACKED_INT_RANGE)==第一个

&& (second& PACKED_INT_RANGE)== second

&& (第三个& PACKED_INT_RANGE)==第三个

&& (第四& PACKED_INT_RANGE)==第四)

{

pPacked [0] =(first& PACKED_INT_RANGE)<< 2;

pPacked [0] | =(second& PACKED_INT_RANGE)>> 4;

pPacked [1] =(second& PACKED_INT_RANGE)<< 4;

pPacked [1] | =(第三& PACKED_INT_RANGE)>> 2;

pPacked [2] =(第三& PACKED_INT_RANGE)<< 6;

pPacked [2] | =(第四& PACKED_INT_RANGE)>> 0;


失败= 0;

}


返回失败;

}

-

- 马克 - >

-



How about the untested:

#define PACKED_INT_RANGE 0x3F /* 6-bits */

/* pPacked had better be 3 bytes or more
*/
int packInts(int first, int second, int third, int fourth, char *pPacked)
{
int failures = !0;

if ((first & PACKED_INT_RANGE) == first
&& (second & PACKED_INT_RANGE) == second
&& (third & PACKED_INT_RANGE) == third
&& (fourth & PACKED_INT_RANGE) == fourth)
{
pPacked[0] = (first & PACKED_INT_RANGE) << 2;
pPacked[0] |= (second & PACKED_INT_RANGE) >> 4;
pPacked[1] = (second & PACKED_INT_RANGE) << 4;
pPacked[1] |= (third & PACKED_INT_RANGE) >> 2;
pPacked[2] = (third & PACKED_INT_RANGE) << 6;
pPacked[2] |= (fourth & PACKED_INT_RANGE) >> 0;

failures = 0;
}

return failures;
}
--
- Mark ->
--





你可以将4个6位值连续存储到32位


我认为你应该试一试,如果你需要额外的帮助,可以发布一些代码。你所需要的只是位移和

位或位和运算符(<>> |&)。

干杯,

Ivan

-





听起来很像家庭作业问题,所以你不太可能在这里获得完整的解决方案。你有没有读过C'的位移和按位

比较运算符?如果没有,请再次询问是否仍需要帮助。


问候,

Tristan


- -

_

_V.-o Tristan Miller [en,(fr,de,ia)]><空间有限

/ |` - '' - = - = - = - = - = - = - = - = - = - = - = - = - = - = - =<> ;在ha句中,所以很难

(7_ \\ ><完成你的工作



Sounds suspiciously like a homework problem, so you''re unlikely to get
complete solutions here. Have you read up on C''s bit-shifting and bitwise
comparison operators? If not, do so and ask again if you still need help.

Regards,
Tristan

--
_
_V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited
/ |`-'' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it''s hard
(7_\\ http://www.nothingisreal.com/ >< To finish what you


这篇关于使用3个字节存储4个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-23 02:17