Home
JAQForum Ver 20.06
Log In or Join  
Active Topics
Local Time 16:41 19 Apr 2024 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

Forum Index : Microcontroller and PC projects : Printing unsigned integers

Author Message
thwill

Guru

Joined: 16/09/2019
Location: United Kingdom
Posts: 3830
Posted: 08:09am 07 Mar 2021
Copy link to clipboard 
Print this post

Hi folks,

I've been having a mental block on this one for 24 hours, even though it feels a bit like a standard interview problem you might ask a graduate programmer.

I want an algorithm to print the unsigned integer corresponding to a negative signed 32 bit integer, e.g. given -254 it will print "4294967042" (a number larger than can be held by a signed 32 bit integer.)

The rub is you only have:

       32 bit integers
       Signed 32-bit arithmetic
       Logical shifts
       Single character printing, i.e. putchar(ch)

Ideally the algorithm would print in an arbitrary base 2 .. 36, but I would settle for base 10 at the moment.

Can anyone help, or point me at a reference?

Best wishes,

Tom
Edited 2021-03-07 18:11 by thwill
Game*Mite, CMM2 Welcome Tape, Creaky old text adventures
 
jirsoft

Guru

Joined: 18/09/2020
Location: Czech Republic
Posts: 532
Posted: 04:01pm 07 Mar 2021
Copy link to clipboard 
Print this post

Hi Tom,
I will simply start so (for negative number, so bit 31 set)
last = inputValue MOD base
last = (256 + last) MOD base
inputValue = inputValue / base


Now you have already inputValue in smaller range (so it can be used same as positive value), you will convert it to base and on the end output also last.

I think this can work...
Jiri
Napoleon Commander and SimplEd for CMM2 (GitHub),  CMM2.fun
 
thwill

Guru

Joined: 16/09/2019
Location: United Kingdom
Posts: 3830
Posted: 04:05pm 07 Mar 2021
Copy link to clipboard 
Print this post

  jirsoft said  Hi Tom,
I will simply start so (for negative number, so bit 31 set)
last = inputValue MOD base
last = (256 + last) MOD base
inputValue = inputValue / base


Now you have already inputValue in smaller range (so it can be used same as positive value), you will convert it to base and on the end output also last.

I think this can work...


Thanks Jiri, I've finessed it for the moment by breaking some of the restrictions, but I will definitely look ath this when I get a moment.

Best wishes,

Tom
Edited 2021-03-08 02:05 by thwill
Game*Mite, CMM2 Welcome Tape, Creaky old text adventures
 
Print this page


To reply to this topic, you need to log in.

© JAQ Software 2024