Path: utzoo!utgpu!watserv1!watmath!att!cbnewsk!cwebb From: cwebb@cbnewsk.att.com (charles.a.webb) Newsgroups: comp.lang.c Subject: Re: IsUnsigned() function? Message-ID: <1990Jul22.025713.10646@cbnewsk.att.com> Date: 22 Jul 90 02:57:13 GMT References: <1990Jul18.001326.5728@druid.uucp> Followup-To: comp.lang.c Organization: AT&T Bell Laboratories Lines: 63 jhsu@Neon.Stanford.EDU (Jeffrey H. Hsu) writes: > Here is a C question I was asked at a Microsoft interview (no, I didn't >get the job...). > How would you write a space efficient algorithm/function in C that >takes in an integer and returns 0 if signed and 1 if unsigned? > IsUnsigned(a) > int a; > { > } Do you really want to test if the int is signed vs unsigned, or positive or negative??? Karl gave an answer to the first question, and indicated that the second question was "trivial." >A non-trivial specification is to write a macro to find the signedness of the >(promoted) type of its argument expression. One way to do this is > #define IsUnsigned(x) (((x)*0-2)/2+1 != 0) > >Karl W. Z. Heuer (karl@kelp.ima.isc.com or ima!kelp!karl), The Walking Lint The answer to the pos vs neg value interpretation of the question can be trivial, but the trivial answer is likely to cause the compiler to generate a compare and branch instruction. If the branches are relatively costly on the machine in question, then perhaps a right shift and xor would be faster. Thus #define IsUnsigned(x) ((((unsigned)(x))>>31)^1) I would be willing to bet that there are some machines that can do this in two instructions - the shift and the xor..... This should be faster and more space efficient on those machines. Note, however, this is highly non-portable, and depends on the sizeof int. a *really* smart compiler should be able to this type of thing automagically, but in my (limited) experience, some compilers can be pretty myopic. If you know all the gory details about the timings of the assembler instructions generated for the particular machine, then you can decide which implementation is most efficient. However, I suspect that in most cases the shift and xor will be faster and more space efficient. (I have assumed a macro since it is silly to use a function call here, especially if the objective is speed!) I have to admit that I'd never have gotten the answer given by Karl (I'm no walking lint :-) However, I might question why you would need such a beast; if the code requires an unsigned int, then specify an unsigned int. IMHO, you should know the type of the expression at compile time, and not have to do this stuff (i.e. don't rely on the default signedness of an int, short or char - if it is important, explicitly declare it or use a cast.) Just some random thoughts. I'd be interested in other opinions. (email) Chip Webb AT&T Bell Labs cwebb@pixels.att.com att!pixels!cwebb (Standard disclaimers apply)