473,583 Members | 3,037 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting hex string to 32 bit signed integer

5 New Member
I have a hex value FFFFFFCE that actually represents -50. When I simply use hex function to convert the above value to an integer, I get 4294967246. That means that integer overflow took place. How do I handle such cases, so that conversion will be correct?
Aug 16 '07 #1
9 33466
KevinADC
4,059 Recognized Expert Specialist
I thought 50 in hex is 32? (16x3+2)
Aug 16 '07 #2
whirly
5 New Member
thanks for your reply. Actually, it is negative 50. I know that if I do the following: $t = hex('ffffffce') & hex('7ffffffff' ); $t = $t - hex('7fffffff') - 1;, I get the correct value of negative 50. But this is clunky.
Aug 16 '07 #3
KevinADC
4,059 Recognized Expert Specialist
I'm lost......... :(
Aug 16 '07 #4
whirly
5 New Member
Sorry. Let me try to clarify. I am trying to convert 8-character hex values to their 32-bit integer representation. The problem arises when a hex string starts with FFFF (ex. FFFFFFCE). I know that the real answer once the conversion is done is "-50" for "FFFFFFCE". You can check it by entering "-50" into any calculator that does conversions, and you will see that the hex value for it is "FFFFFFCE". But if you enter "FFFFFFCE" first and try to convert it to an integer, you will get "4294967246 ", which indicates overflow. My current solution is to subtract the maxint value (FFFFFFFF) from the given value (FFFFFFCE) and to subtract 1 from the result, which will yield the correct value of "-50". I don' t know if that is the best way and also if there are any other gotchas. I would imagine underflow will also present problems.
Aug 16 '07 #5
numberwhun
3,509 Recognized Expert Moderator Specialist
Have you tried using the Data::Translate module from cpan? It looks like it does conversions like the one you are looking to do.

Regards,

Jeff
Aug 17 '07 #6
whirly
5 New Member
Thank you, Jeff. I will check it out.
Aug 17 '07 #7
miller
1,089 Recognized Expert Top Contributor
Sorry. Let me try to clarify. I am trying to convert 8-character hex values to their 32-bit integer representation.
Actually, what you are trying to do is convert an 8 character hex string to a 32-bit SIGNED integer, at least according to the specification from Java or C. The problem you have is that there is no such thing as a strictly 32-bit integer in perl, so you must code the rules yourself or use a module as Jeff suggested.

Fortunately, the rules are fairly simple. But let's start with unsigned first:
unsigned int
Dec: 0 to 4_294_967_295 (2^32-1)
Hex Representation: 0x00000000 to 0xFFFFFFFF
As you can see, straight forward enough. And the hex translation can be handled directly with the hex function and sprintf.

Signed integers are a little harder. The positive range is handled easily enough. However, the negative range is indicated by the 32nd bit, and the values are stored opposite of the positive range. This made arithmetic simpler back in the "old days" I suspect.

signed int
Dec: (-1 * 2 ^ 31) -2_147_483_648 to 2_147_483_647 (2 ^ 31 - 1)
hex positive: 0x00000000 to 0x7FFFFFFF
hex negative: 0xFFFFFFFF to 0x80000000
The easiest way to code your own translation function would be to rely on a little bit arithmetic:

Expand|Select|Wrap|Line Numbers
  1. print hexstr_to_signed32int('FFFFFFCE'), "\n"; # Outputs -50
  2. print signed32int_to_hexstr(-50), "\n"; # Outputs ffffffce
  3.  
  4. sub hexstr_to_signed32int {
  5.     my ($hexstr) = @_;
  6.     die "Invalid hex string: $hexstr"
  7.         if $hexstr !~ /^[0-9A-Fa-f]{1,8}$/;
  8.  
  9.     my $num = hex($hexstr);
  10.     return $num >> 31 ? $num - 2 ** 32 : $num;
  11. }
  12.  
  13. sub signed32int_to_hexstr {
  14.     my ($num) = @_;
  15.     die "Number outside of signed 32-bit range: $num"
  16.         if $num > 2_147_483_647 or $num < -2_147_483_648;
  17.  
  18.     my $unsigned = $num < 0 ? 2 ** 32 + $num : $num;
  19.     return sprintf "%x", $unsigned;
  20. }
  21.  
If you wanted capital hex strings, just change %x to %X

- Miller
Aug 23 '07 #8
whirly
5 New Member
Thank you so much!!!
Sep 6 '07 #9
Phatfingers
2 New Member
Really great answer! Your thorough explanation helped me with a loosely related issue in creating a hashing function compatible with ones we use in Java and C. Perl had the binary result intact, but just needed a little adjustment to represent it as an unsigned integer value. Much appreciated.

The problem you have is that there is no such thing as a strictly 32-bit integer in perl, so you must code the rules yourself or use a module as Jeff suggested.
...
Expand|Select|Wrap|Line Numbers
  1.     return $num >> 31 ? $num - 2 ** 32 : $num;
  2.  
- Miller
Jul 25 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
11146
by: ken | last post by:
I've been looking for a solution to a string to long conversion problem that I've run into >>> x = 'e10ea210' >>> print x e10ea210 >>> y=long(x) Traceback (most recent call last): File "<pyshell#2>", line 1, in ? y=long(x)
5
2202
by: nickisme | last post by:
Hi - sorry for the possibly stupid question, but I'm still a wee starter on c++... Just wondering if there's a quick way to convert data into binary strings... To explain, I'm trying to convert numbers into 16 bit binary form, so that I can eventually alter the LSB for dithering purposes. Obviously I can create my own function that will do...
25
6669
by: TK | last post by:
I'm used to programming in c or c++ in which my problem is simple. I want to be able to enter a value on a page (like 3.2), and then read it as a 32-bit float and break it into it's individual bytes. I've tried using bitwise operators, but they seem to convert the value into an integer first, and i've tried using the toString() method to...
2
5745
by: Asbjørn Ulsberg | last post by:
Hi. I'm trying to convert Brady Hegberg's great RTF2HTML VB 6.0 module to C#. I've managed to convert the VB code to VB.NET, which gave me the following code: Option Strict On Option Explicit On Option Compare Binary
7
2841
by: Robin Haswell | last post by:
Hey guys. This should just be a quickie: I can't figure out how to convert r"\x2019" to an int - could someone give me a hand please? Cheers -Rob
11
3353
by: TomServo | last post by:
I am writing code that needs to run on a variety of Unix systems. I am calling the statvfs and statfs system calls and I need to to convert some of the integers returned to character strings. Normally I would do this using sprintf as so: sprintf(&buffer, "%lu", integer); The problem is that I will not know if the integer values I am...
9
2553
by: Terry | last post by:
I am converting (attempting) some vb6 code that makes vast use of interfaces. One of the major uses is to be able to split out Read-only access to an obect. Let me give you a simple (contrived) example: In Project RoObjDefs: RoPerson.cls file: Public Property Get FirstName() as String Public Property Get LastName() as String <end of file...
7
5035
by: somenath | last post by:
Hi All, I am trying to undestand "Type Conversions" from K&R book.I am not able to understand the bellow mentioned text "Conversion rules are more complicated when unsigned operands are involved. The problem is that comparisons between signed and unsigned values are machine- dependent, because they depend on the sizes of the various...
5
12632
by: Hans Mull | last post by:
Hi! How can I convert a string to a const unsigned char*? (string::c_str() converts the string to a signed char) Thanks in advance, Hans
0
7815
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8168
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7926
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6573
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5691
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3812
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1418
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1149
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.