简体   繁体   English

将数字转换为十六进制

[英]Convert number to hex

I use sprintf for conversion to hex - example >> 我使用sprintf转换为十六进制-示例>>

$hex = sprintf("0x%x",$d)

But I was wondering, if there is some alternative way how to do it without sprintf . 但是我在想,如果没有sprintf ,还有其他方法可以做到这一点。

My goal is convert a number to 4-byte hex code (eg 013f571f ) 我的目标是将数字转换为4字节的十六进制代码(例如013f571f

Additionally (and optionally), how can I do such conversion, if number is in 4 * %0xxxxxxx format, using just 7 bits per byte? 另外(和可选),如果数字为4 * %0xxxxxxx格式,每字节仅使用7位,该如何进行转换?

sprintf() is probably the most appropriate way. sprintf()可能是最合适的方法。 According to http://perldoc.perl.org/functions/hex.html : 根据http://perldoc.perl.org/functions/hex.html

To present something as hex, look into printf , sprintf , and unpack . 要以十六进制形式显示内容,请查看printfsprintfunpack

I'm not really sure about your second question, it sounds like unpack() would be useful there. 我不太确定您的第二个问题,听起来unpack()在这里很有用。

My goal is convert a number to 4-byte hex code (eg 013f571f) 我的目标是将数字转换为4字节的十六进制代码(例如013f571f)

Hex is a textual representation of a number. 十六进制是数字的文本表示形式。 sprintf '%X' returns hex (the eight characters 013f571f ). sprintf '%X'返回十六进制(八个字符013f571f )。 sprintf is specifically designed to format numbers into text, so it's a very elegant solution for that. sprintf是专门设计用于将数字格式化为文本的,因此它是一个非常优雅的解决方案。

...But it's not what you want. ...但这不是您想要的。 You're not looking for hex, you're looking for the 4-byte internal storage of an integer. 您不是在寻找十六进制,而是在寻找一个整数的4字节内部存储。 That has nothing to do with hex. 这与十六进制无关。

pack 'N', 0x013f571f;  # "\x01\x3f\x57\x1f" Big-endian byte order
pack 'V', 0x013f571f;  # "\x1f\x57\x3f\x01" Little-endian byte order

sprintf() is my usual way of performing this conversion. sprintf()是我执行此转换的常用方法。 You can do it with unpack, but it will probably be more effort on your side. 您可以通过解压缩来完成此操作,但是这可能需要更多的精力。

For only working with 4 byte values, the following will work though (maybe not as elegant as expected!): 对于仅使用4个字节的值,以下方法将起作用(也许不如预期的那么优雅!):

print unpack("H8", pack("N1", $d));

Be aware that this will result in 0xFFFFFFFF for numbers bigger than that as well. 请注意,对于大于该数字的数字,这也会导致0xFFFFFFFF。

For working pack/unpack with arbitrary bit length, check out http://www.perlmonks.org/?node_id=383881 有关具有任意位长的工作pack/unpack ,请访问http://www.perlmonks.org/?node_id=383881

The perlpacktut will be a handy read as well. perlpacktut也将很方便地阅读。

For 4 * %0xxxxxxx format, my non- sprintf solution is: 对于4 * %0xxxxxxx格式,我的non- sprintf解决方案是:

print unpack("H8", pack("N1", 
  (((($d>>21)&0x7f)<<24) + ((($d>>14)&0x7f)<<16) + ((($d>>7)&0x7f)<<8) + ($d&0x7f))));

Any comments and improvements are very welcome. 任何意见和改进都非常欢迎。

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

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