如何存储ascii数字4位而不是整个字节 [英] how to store ascii digit 4 bits instead of the whole byte

查看:56
本文介绍了如何存储ascii数字4位而不是整个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

i我正在尝试使用字符串操作自己实现一个大的int类





但是由于每个字符串数字占用8位存储器,我想使用4位作为数字,而不是整个字节。因此,数字123,456可能由字节12 34 56而不是字符串123456表示。(三个字节而不是六个字节。)



帮助请;

hello
i am trying my own implementation of a big int class using string manipulation


but since each string digit takes up 8 bits of memory i want to use 4 bits for the digit, instead of the whole byte. Thus, the number 123,456 might be represented by the bytes 12 34 56 instead of the string 123456. (Three bytes as opposed to six.)

help please ;

推荐答案

你想要的是BCD。



二进制编码的十进制 - 维基百科,免费的百科全书 [ ^ ]



当以十六进制形式查看时,十进制数字对看起来像十进制。



What you want is BCD.

Binary-coded decimal - Wikipedia, the free encyclopedia[^]

When viewed as hexadecimal, the decimal digit pair appear like decimal.

const char *text = "123456";

std::vector<unsigned char> number;

while (*text)
{
    unsigned char pair = 0;
    unsigned char digit = *text++;
    digit -= '0';
    pair = digit;
    if (*text)
    {
        digit = *text++;
        digit -= '0';
        pair <<= 4;
        pair |= digit;
    }
    number.push_back(pair);
}

for (int i = 0; i < number.size())
{
    printf("%02X", number[i]);
}


查看我的文章对按位运算符的介绍 [ ^ ]。您可以使用AND,OR和SHIFT运算符完成您想要的任务。
Have a look at my article An introduction to bitwise operators[^]. You can accomplish what you want using the AND, OR, and SHIFT operators.


这篇关于如何存储ascii数字4位而不是整个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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