数组到十六进制表示
我正在编写一个程序,需要获取大小为 n 的数组并将其转换为十六进制值,如下所示:
int a[] = { 0, 1, 1, 0 };
我想将数组的每个值表示为二进制并将其转换为十六进制值。在本例中:
0x6000000000000000; // 0110...0
它还必须用 0 填充到右侧才能成为 64 位(我在 64 位机器上)。
或者我也可以获取数组元素,转换为十进制并转换为十六进制,这样更容易...在 C++ 中执行此操作的最佳方法是什么?
(这不是家庭作业)
I am writing a program that needs to take an array of size n and convert that into it's hex value as follows:
int a[] = { 0, 1, 1, 0 };
I would like to take each value of the array to represent it as binary and convert it to a hex value. In this case:
0x6000000000000000; // 0110...0
it also has to be packed to the right with 0's to be 64 bits (i am on a 64 bit machine).
Or i could also take the array elements, convert to decimal and convert to hexadecimal it that's easier... What you be the best way of doing this in C++?
(this is not homework)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
下面假设您的
a[]
将仅使用 0 和 1 来表示位。您还需要指定数组长度,在这种情况下可以使用 sizeof(a)/sizeof(int) ,但不适用于堆分配的数组。另外,result
需要是 64 位整数类型。如果您想查看十六进制形式,可以使用
(s)printf( "%I64x", result )
The following assumes that your
a[]
will only ever use 0 and 1 to represent bits. You'll also need to specify the array length,sizeof(a)/sizeof(int)
can be used in this case, but not for heap allocated arrays. Also,result
will need to be a 64bit integer type.If you want to see what it looks like in hex, you can use
(s)printf( "%I64x", result )
std::bitset<64>::to_ulong()
可能是你的朋友。顺序可能会向后(未指定,但通常会通过将单词右移 3 并用 1 进行掩码来获取索引 3),但您可以通过从 63 中减去所需的索引来解决这个问题。std::bitset<64>::to_ulong()
might be your friend. The order will probably be backwards (it is unspecified, but typically index 3 will be fetched by right-shifting the word by 3 and masking with 1), but you can remedy that by subtracting the desired index from 63.假设:
a[]
最多 64 个条目,在编译时定义,并且仅包含1
或0
。在编译时定义可以避免左移 64 的问题,因为您不能声明空数组。Assumptions:
a[]
is at most 64 entries, is defined at compile time, and only contains1
or0
. Being defined at compile time sidesteps issues of shifting left by 64, as you cannot declare an empty array.这是一个粗略的答案:
Here's a rough answer:
字节十六进制值[16];
for(int i = 15; i >= 0; i--)
{
十六进制值 = a[i*4] * 8 + a[i*4-1] * 4 + [i*4-2] * 2 + a[i*4-3];
这
将为您提供一个字节数组,其中每个字节代表您的一个十六进制值。
请注意,hexValues 中的每个字节都是 0 到 16 之间的值。
byte hexValues[16];
for(int i = 15; i >= 0; i--)
{
hexValues = a[i*4] * 8 + a[i*4-1] * 4 + [i*4-2] * 2 + a[i*4-3];
}
This will give you an array of bytes where each byte represents one of your hex values.
Note that each byte in hexValues will be a value from 0 to 16.