How to use Cshort in Julia

I have a 16-bit hex string a = "4E1A". How to convert a to signed short integer using Cshort. No example usage is found for Cshort.

julia> reinterpret(Int16,[0x4E1A])
1-element reinterpret(Int16, ::Vector{UInt16}):

julia> 10 + 1*16 + 14 * 16^2 + 4 * 16^3

How to convert a = “4E1A” to 0x4E1A

julia> parse(Int, "4E1A", base=16)
julia> parse(Int16, "4E1A", base=16)

Do you want to parse it?

julia> parse(UInt16, "4E1A"; base=16)
1 Like

julia> parse(Int16, “F1CF”, base=16)
ERROR: OverflowError: overflow parsing “F1CF”
[1] tryparse_internal(#unused#::Type{Int16}, s::String, startpos::Int64, endpos::Int64, base_::Int64, raise::Bool)
@ Base .\parse.jl:163
[2] parse(::Type{Int16}, s::String; base::Int64)
@ Base .\parse.jl:241
[3] top-level scope
@ REPL[4]:1

That’s because this is larger than the largest positive Int16. If you want to “wrap it around” to a negative Int16 value with those bytes via 2’s complement, do:

julia> parse(UInt16, "F1CF"; base=16) % Int16
1 Like

There’s nothing special or different about Cshort. The only reason you’d ever want to use it is for interop with a C program that uses the definition of short. Otherwise, it’s much better to simply use Int16 directly as folks here are assuming because it seems you know that it’s two bytes (or four hex digits).

Why “F1CF” is larger than largest positive Int16 (32767). Is it by convention. Can you please explain. There are total 2^16 different values possible with Int16. Of which many are causing overflow error. How can I find out which possible values are causing overflow error.

C short is a 16-bit signed integer (as is Int16) and so it can store values in the range -2^15 to 2^15-1. That is, the largest positive value is 7FFF.

A C unsigned short is equivalent to a UInt16 and can store values from 0 to 2^16-1 (ie up to FFFF).