PDA

View Full Version : Curious side effect of data type casting in VAL() function ?



dco045
06-04-2018, 18:20
Hi,

The following thin basic example is from a program wich extracts data from a microprocessor development board.
The uploaded file contains formatted lines. The first field, on 4 chars is the hexadecimal address of data in the following fields.
ex: 02AF 01A23F65E47CD089

The data is entered in a string array , at the address extracted from first field. Extracted as a 4 char string. Dim hex_addr As String * 4
The addresses are gathered without any order.

the string array is dimensioned as 2^16 pairs of hex chars, so the position of a byte in the array is
(addresse*2)+1
The position in the array from 1 to 131072 has to be coded in a dword integer.

To convert the 4 hex chars address I use pos_in_array = Val("&h" & hex_addr )

But when the address is = 0x7fff the returned value is 32767




= 0x8000 the returned value is 4294934528 , Val("&h8000) is considered as negative !


The workaround I found is to add a zero to the string before conversion.

See examples


Uses "Console"

Dim hex_addr As String * 4
Dim data_array as string * 131072
Dim pos_in_array_w As Word
Dim pos_in_array_dw As DWord

hex_addr = "4000"
pos_in_array_w = Val( "&h" & hex_addr )
pos_in_array_dw = Val( "&h" & hex_addr )
PrintL hex_addr ,, pos_in_array_w , pos_in_array_dw

hex_addr = "7FFf"
pos_in_array_w = Val( "&h" & hex_addr )
pos_in_array_dw = Val( "&h" & hex_addr )
PrintL hex_addr ,, pos_in_array_w , pos_in_array_dw

hex_addr = "8000"
pos_in_array_w = Val( "&h" & hex_addr )
pos_in_array_dw = Val( "&h" & hex_addr )
PrintL hex_addr ,, pos_in_array_w , pos_in_array_dw

hex_addr = "fff0"
pos_in_array_w = Val( "&h" & hex_addr )
pos_in_array_dw = Val( "&h" & hex_addr )
PrintL hex_addr ,, pos_in_array_w , pos_in_array_dw

hex_addr = "8000"
pos_in_array_w = Val( "&h" & hex_addr )
pos_in_array_dw = Val( "&h0" & hex_addr )
PrintL hex_addr ,, pos_in_array_w , pos_in_array_dw

hex_addr = "fff0"
pos_in_array_w = Val( "&h" & hex_addr )
pos_in_array_dw = Val( "&h0" & hex_addr )
PrintL hex_addr ,, pos_in_array_w , pos_in_array_dw

PrintL "---------------"
pos_in_array_w = Val( "&h8000" )
pos_in_array_dw = Val( "&h8000" )
PrintL "&h8000" ,, pos_in_array_w , pos_in_array_dw

pos_in_array_w = Val( "&h08000" )
pos_in_array_dw = Val( "&h08000" )
PrintL "&h08000" ,, pos_in_array_w , pos_in_array_dw

PrintL "direct"
PrintL "&h08000" ,, Val( "&h08000" )
PrintL "&h8000" ,, Val( "&h8000" )


PrintL "Press a key to end program"
WaitKey

Best regards.


Dany

Petr Schreiber
21-04-2018, 20:57
Hi Dany,

this is by design, inherited from convention in PowerBASIC. But I agree it should be mentioned in the documentation.


Petr

ErosOlmi
23-04-2018, 10:18
Yes, sorry: I wanted to reply but forgot it.
I will change help and possibly add some specific HEX functions.