Skip to content

Instantly share code, notes, and snippets.

@ptantiku
Last active August 29, 2015 14:15
Show Gist options
  • Save ptantiku/3da5932db9e1fade8034 to your computer and use it in GitHub Desktop.
Save ptantiku/3da5932db9e1fade8034 to your computer and use it in GitHub Desktop.
Convert bit stream into ASCII string
#####################################################################
# converting bit stream into ascii string #
# author: ptantiku #
# #
# compile: gcc conv_bin2str.s -o conv_bin2str #
# usage: conv_bin2str <binary string> #
# example: conv_bin2str 0110100001100101011011000110110001101111 #
#####################################################################
.data
teststr:
.string "0110100001100101011011000110110001101111"
helpstr:
.string "usage: conv_bin2str <binary string>"
.text
.global main
main:
pushq %rbp
movq %rsp, %rbp
cmp $1, %rdi # ARG==1?
je print_help
#push (%rsi) # save ARGV[0] in the stack
push 8(%rsi) # save ARGV[1] in the stack
movq (%rsp), %rsi # set source address
movq (%rsp), %rdi # set destination address
xor %rcx, %rcx #empty for counting
xor %bl, %bl #empty for store result for each byte
mov $8, %dl #set dl=8 for modulo
loop:
lodsb #load byte from rsi to al
cmp $0, %al
je finish #when string terminator found, exit loop
inc %ecx
# push a bit into %bl
shl $1, %bl
and $1, %al #'0'=0x30, '1'=0x31
add %al, %bl
# test if count mod 8 == 0
mov %ecx, %eax
idiv %dl
test %ah, %ah
jne loop
# if complete the 8 bits, store the byte, and reset
movb %bl, %al
stosb
xor %bl, %bl
jmp loop
finish:
# ignore what left in %bl,
# input must be 8-multiple bytes only
movb $0, %al #add string terminator
stosb
print_result:
# print result
movq (%rsp), %rdi #reload the address to print
call puts
movq $0, %rax
jmp exit
print_help:
# print help
movq $helpstr, %rdi
call puts
movq $0, %rax
exit:
leave
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment