# Thread: Convert string to signed hex

1. ## Convert string to signed hex

Hi, as part of my program i have to read in 6 digit (24bit) hex values as strings and then convert them. This works fine with the strtol function until i hit values where the most significant digit is greater than 7 (i.e. a negative value).

Eg. I read in FFFFFF, in my program this should be read as -1 however
Code:
`strtol(string, NULL, 16)`
returns 16777215.

Is there a function which takes the sign bit into account? Also sorry if i'm making no sense, i'm a tard when it comes to sign bits  2. FFFFFF is not equal to -1 on most systems.
FFFFFFFF is equal to -1.

So the most significant bit isn't set to 1; it has 8 more bits that are 0. 3. Alright, well then how do i get a function to work with 24bits instead of 32? 4. Well... you could compare the result with 0x7FFFFF. If it's greater than that, then you can change the result by subtracting 0x1000000 from it. 5. Originally Posted by boblettoj99 Alright, well then how do i get a function to work with 24bits instead of 32?
strtol() doesn't even work that way for 32 bit numbers since a long is often 8 bytes. 6. Originally Posted by EVOEx Well... you could compare the result with 0x7FFFFF. If it's greater than that, then you can change the result by subtracting 0x1000000 from it.
Or, you could test the hob of the 24 bit number, and pad to the left with X'FF's if on.

As in
Code:
`if (24_bit_value & 0x00800000) 24_bit_value |= 0xFF000000 ;`
Or, since you are working with strings, you could test the first char too:

Code:
```char newstring = {0} ;
if ( string == '8' || string== '9' || (toupper(string >= 'A' && toupper(string <= 'F') ) {
strcat(newstring, "FF") ;
strcat(newstring, string) ;
}
else  strcpy(newstring, string) ;```
(not syntax checked) 7. @Dino: that makes further assumptions that aren't completely portable. First of all, MK27's point that a long is usually not even 32 bits but 64. But even if you would pad more bits, it still wouldn't be portable. It would still assume a bit size that isn't always true (64 bits), and also 2s complement is assumed, which isn't always true (though I've never seen a system run that doesn't use 2s complement). 8. @EVOEx - with illustrations, all those assumptions are left to the OP to worry about.  9. Originally Posted by EVOEx @Dino: that makes further assumptions that aren't completely portable.
Who said anything about portability? He's talking about wanting 24 bit integers. Quzah. Popular pages Recent additions 