Created
October 9, 2012 03:10
-
-
Save clicube/3856353 to your computer and use it in GitHub Desktop.
add xor method to String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
require_relative 'string_xor' | |
"hoge".xor("fuga") #=> "\x0E\x1A\x00\x04" | |
# 非破壊的です |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ruby.h> | |
// ref: http://d.hatena.ne.jp/okmount/20090223/1235317264 | |
VALUE string_xor(VALUE str1, VALUE str2) | |
{ | |
if(RSTRING_LEN(str1) != RSTRING_LEN(str2)) | |
{ | |
return Qnil; | |
} | |
VALUE result = rb_str_new(RSTRING_PTR(str1), RSTRING_LEN(str1)); | |
int i; | |
for (i = 0; i < RSTRING_LEN(str1); i++) | |
{ | |
RSTRING_PTR(result)[i] ^= RSTRING_PTR(str2)[i]; | |
} | |
return result; | |
} | |
void Init_string_xor(void) | |
{ | |
VALUE cString = rb_define_class("String", rb_cObject); | |
rb_define_method(cString, "xor", string_xor, 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment