Skip to content

Instantly share code, notes, and snippets.

@clicube
Created October 9, 2012 03:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clicube/3856353 to your computer and use it in GitHub Desktop.
Save clicube/3856353 to your computer and use it in GitHub Desktop.
add xor method to String
# coding: utf-8
require_relative 'string_xor'
"hoge".xor("fuga") #=> "\x0E\x1A\x00\x04"
# 非破壊的です
#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