将四个字符串转换为长字符串 [英] Converting a four character string to a long

查看:53
本文介绍了将四个字符串转换为长字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将四个字符串(即四个字符)转换为长字符串(即,将其转换为ASCII码,然后将其放入长字符串中).

I want to convert a four character string (i.e. four characters) into a long (i.e. convert them to ASCII codes and then put them into the long).

据我了解,这是通过将第一个字符写入long的第一个字节,将第二个字符写入相邻的内存位置等来完成的.但是我不知道如何在C ++中做到这一点.

As I understand it, this is done by writing the first character to the first byte of the long, the second to the adjacent memory location, and so on. But I don't know how to do this in C++.

有人可以指出我正确的方向吗?

Can someone please point me in the right direction?

谢谢.

推荐答案

这是您设置的四个字符:

Here's your set of four characters:

const unsigned char buf[4] = { 'a', '0', '%', 'Q' };

现在,我们组装一个32位无符号整数:

Now we assemble a 32-bit unsigned integer:

const uint32_t n = (buf[0]) | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

在这里,我认为 buf [0] 是最低有效位;如果您想反过来,只需交换索引即可.

Here I assume that buf[0] is the least significant one; if you want to go the other way round, just swap the indices around.

我们确认:

printf("n = 0x%08X\n", n); // we get n = 0x51253061
                           //               Q % 0 a

重要提示:请确保您的原始字节缓冲区为 unsigned ,否则,请添加显式强制类型转换,例如(unsigned int)(unsigned char)(buf [i]);否则,移位操作将无法很好地定义.

Important: Make sure your original byte buffer is unsigned, or otherwise add explicit casts like (unsigned int)(unsigned char)(buf[i]); otherwise the shift operations are not well defined.

警告语:我强烈希望这种代数方法胜于可能诱人的 const uint32_t n = *(uint32_t *)(buf),这是机器字节序如果您使用严格的别名假设,将使您的编译器感到愤怒!

Word of warning: I would strongly prefer this algebraic solution over the possibly tempting const uint32_t n = *(uint32_t*)(buf), which is machine-endianness dependent and will make your compiler angry if you're using strict aliasing assumptions!

正如下面有帮助的指出的那样,您可以通过不对字节的位大小进行假设来尝试并变得更加可移植:

As was helpfully pointed out below, you can try and be even more portable by not making assumptions on the bit size of a byte:

const unsigned very long int n = buf[0] |
              (buf[1] << (CHAR_BIT)     |
              (buf[2] << (CHAR_BIT * 2) |
              (buf[3] << (CHAR_BIT * 3)   ;

可以根据需要随意编写自己的概括!(祝您找到合适的 printf 格式字符串;-).)

Feel free to write your own generalizations as needed! (Good luck figuring out the appropriate printf format string ;-) .)

这篇关于将四个字符串转换为长字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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