Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

[REBOL] Re: bit shifts

From: greggirwin:starband at: 11-Sep-2001 15:31

Hi Hallvard, << How do I use rebol for bit shifts? I feel like shifting the binary string 11101000 four places to the right, so it becomes "00001110". How do I do that?? >> If you're working with numeric values you can multiply or divide, by powers of two. For example (please correct any misinformation REBOLers!): shl: to-integer (value * (2 ** shift-count)) shr: to-integer (value / (2 ** shift-count)) That doesn't account for sign bits, negative numbers, and such but it's the general idea. If you have binary strings of 0 and 1 digits, maybe this will help: left: func [s len][return copy/part s len] right: func [s len][return copy at s ((length? s) - (len - 1))] mid: func [s start len][return copy/part at s start len] mk-string: func [n[integer!] ch[char! string!]][to-string array/initial n ch] bin-str: func [{Converts a string to a string of 1's and 0's, 1 per bit} s[string!]] [enbase/base s 2] unbin-str: func [{Converts a string from a string of 1's and 0's, 1 per bit, to a text string.} s[string!]] [to-string debase/base s 2] bin-str-shl: func [{Shifts a text string of 1's an 0's count "bits" left.} s[string!] count[integer!]] [ join mid s (count + 1) ((length? s) - count) mk-string count "0" ] bin-str-shr: func [{Shifts a text string of 1's an 0's count "bits" right.} s[string!] count[integer!]] [ join mk-string count "0" mid s 1 ((length? s) - count) ] bin-str-rol: func [{Rotates a text string of 1's an 0's count "bits" left.} s[string!] count[integer!]] [ join (mid s (count + 1) ((length? s) - count)) (left s count) ] bin-str-ror: func [{Rotates a text string of 1's an 0's count "bits" right.} s[string!] count[integer!]] [ join (right s count) mid s 1 ((length? s) - count) ] bin-str-val: func [s[string!]] [to-integer debase/base s 2] --Gregg