简体   繁体   English

每4位解释为十六进制值

[英]Interpreting every 4 bits as hex value

I am having a some trouble interpreting bits as bytes. 将位解释为字节时遇到一些麻烦。 What I have now is a string of either 8, 16, 24, etc. bits and I want to convert them into hex bytes. 我现在拥有的是8、16、24等位的字符串,我想将它们转换为十六进制字节。 For example: 例如:

Lets say I have the following strings: 可以说我有以下字符串:

10100101 00110000 10100101 00110000

And I want to interpret each 4 as hex bytes so I would have 我想将每个4解释为十六进制字节,这样我就可以

1010 as A, 0101 as 5, 0011 as 3, and 0000 as 0 1010为A,0101为5,0011为3,0000为0

Then when I put them together, I should get 那我把它们放在一起的时候

A5 30 which would correspond to ¥0 based on their individual hex value. A5 30,根据其各自的十六进制值,它对应于¥0。 I'm not entirely sure on how to do this unfortunately. 不幸的是,我不确定如何执行此操作。 Might anyone have an idea to do this? 可能有人有想法这样做吗? If so, that'd be great! 如果是这样,那就太好了! Thanks! 谢谢!

This problem was already solved for you , in the C++ Standard Library's <bitset> header: 在C ++标准库的<bitset>标头中, 已经为您解决了此问题:

const unsigned long value1 = std::bitset<8>(std::string("10100101")).to_ulong();
const unsigned long value2 = std::bitset<8>(std::string("00110000")).to_ulong();

std::cout << std::hex << value1 << " " << std::hex << value2 << '\n';

You should convert each individual group of 4 bits to one character, eg. 您应该将每个单独的4位组转换为一个字符,例如。 with a table: 带桌子:

 char Hex[16]={ '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

A generic way to calculate this (without libraries between any 2 BASES) is to: 一种通用的计算方式(在任何2个BASE之间没有库)是:

Step 1) 第1步)

  my_number = 0; // start to read digits.
  while((a = read_digit(BASE))>=0) { 
       // read_digit should return -1 for non digit
       my_number=my_number * BASE + a;
       // optionally: if (count++ == 4) break;  /* read only 4 bits or digits */
  }

Step 2) 第2步)

  // convert my_number to another base (eg. hex or decimal or octal or Base64)
  // by repeated division by BASE and storing the modulus
  while (my_number) {
       int modulus = my_number % BASE;
       my_number/=BASE;
       PUSH(modulus);
  }

Step 2.5) 步骤2.5)

  // Pop the numbers in range (0..BASE-1) from stack 
  // to output them from left to right
  while (POP(my_number) >=0) {     // assumes that pop returns <0 when empty
      cout << myTable[my_number];  // this can be selected for any base
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM