BSD Checksum

Share your advanced PureBasic knowledge/code with the community.
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3942
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

BSD Checksum

Post by wilbert »

http://en.wikipedia.org/wiki/BSD_checksum
Simple and fast

Code: Select all

Procedure BSD_Sum(*Buffer, Size, InitialValue = 0)
  EnableASM
  CompilerIf #PB_Compiler_Processor = #PB_Processor_x86
    MOV edx, *Buffer
    MOV ecx, Size
    MOV eax, InitialValue
    !push ebx
    !bsd_sum_loop:
    !ror ax, 1
    !movzx bx, byte [edx]
    !add ax, bx
    !inc edx
    !dec ecx
    !jnz bsd_sum_loop
    !pop ebx
    !movzx eax, ax
  CompilerElse
    MOV r8, *Buffer
    MOV rcx, Size
    MOV rax, InitialValue
    !bsd_sum_loop:
    !ror ax, 1
    !movzx dx, byte [r8]
    !add ax, dx
    !inc r8
    !dec rcx
    !jnz bsd_sum_loop
    !movzx rax, ax    
  CompilerEndIf
  DisableASM
  ProcedureReturn
EndProcedure


; test the code

If ReadFile(0, "MyFile")
  Size = Lof(0)
  *buf = AllocateMemory(Size)
  ReadData(0, *buf, size)
  CloseFile(0)
EndIf

Debug BSD_Sum(*buf, size)