Skip to content

Instantly share code, notes, and snippets.

@dockimbel
Created July 3, 2011 08:51
Show Gist options
  • Save dockimbel/1062078 to your computer and use it in GitHub Desktop.
Save dockimbel/1062078 to your computer and use it in GitHub Desktop.
Attempt to reproduce issue #120 (Type-casting of string element to integer does not work)
Red/System []
#import [
"msvcrt.dll" cdecl [ ; Windows
calloc: "calloc" [ ; Allocate zero-filled memory.
chunks [integer!]
size [integer!]
return: [c-string!]
]
memcpy: "memcpy" [ ; Copy memory range.
target [c-string!]
source [c-string!]
size [integer!]
return: [c-string!]
]
]
]
max: func [
i1 [integer!]
i2 [integer!]
return: [integer!]
][
either i1 > i2 [i1][i2]
]
min: func [
i1 [integer!]
i2 [integer!]
return: [integer!]
][
either i1 < i2 [i1][i2]
]
make-string: func [
; allocates space for string
n [integer!] ; length of string
return: [c-string!]
][
as c-string! calloc n + 1 1
]
copy-part: func [
; implements sub-stringing
s [c-string!] ; pointer to string to be copied
n [integer!] ; number of characters to be copied
return: [c-string!] ; a pointer to a new string
/local r [c-string!]
][
n: max n 0 ; do not crash
n: min n length? s ; idem
r: make-string n
memcpy r s n
r
; note: the memory area pointed to by r has to be de-allocated
; by the user himself (no GC)
]
form-signed: func [
i [integer!]
return: [c-string!]
/local s [c-string!] r [c-string!] c [integer!] n [logic!]
][
if zero? i [return "0"]
s: make-string 11
n: negative? i
if n [i: negate i]
c: 11
while [i <> 0][
s/c: #"0" + (i // 10)
i: i / 10
c: c - 1
]
if n [s/c: #"-" c: c - 1]
r: copy-part s + c 11 - c
free as byte-ptr! s
r
]
printf: func [
i [integer!]
][
print form-signed i
]
s: "abcd" printf as integer! s/1 ; should give 97, gives an address value
s: "abcd" b: s/1 printf as integer! b ; gives 97 alright
@meijeru
Copy link

meijeru commented Jul 3, 2011

Wen I run the above gist it works OK. It must be something in my own version of form-signed. I have made a few adaptations since putting it up on gist. Let's forget it.

@dockimbel
Copy link
Author

Ok, I let you close issue #120 then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment