中文圈程序员的碎碎念
509 subscribers
3.52K photos
21 videos
129 files
28.7K links
嘿!你也来看码农又在写啥BUG了吗
Download Telegram
TIL: quick facts I learned

The RC 4000 Multiprogramming System is historically notable for being the first attempt to break down an operating system into a group of interacting programs communicating via a message passing kernel. RC 4000 was not widely used, but was highly influential, sparking the microkernel concept that dominated operating system research through the 1970s and 1980s. (wikipedia)

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
指针传参hack

c语言中有时会看到 void * data 这样的类型,可以通过cast转换为任意需要的数据指针。C语言中的pointer一般为 4 Bytes 也即 32 位。当传递的参数不大时,完全可以把一个int塞进这个指针中传递,从而省下了申请内存的麻烦。

一个常见的例子是,在GUI编程中为按钮绑定点击事件。

1


Widget MakeButton(char *label, ButtonCB function, void *data);

其中

1


typedef void (*ButtonCB)(Widget w, void *data);

为按钮绑定一个点击事件func,假设func需要接受一个整数参数,这里可以这样写

1
2
3
4
5


void func(void *data){
int x = (int) data;

// TODO
}

可以强行把一个整数塞进指针的32位存储空间中。但注意一般整数为64位,这样做有可能导致溢出。

解决办法是:使用 intptr_t 类型,它在stdint.h中。这个类型其实就是32位的整数。对应地,可以这样:

1


intptr_t x = (intptr_t)data;


via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
this is a test page. nothing interesting here. EUPL-1.2

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
PubKey


$ curl -S https://shrik3.com/misc/gpg.asc | gpg --import

220F 6A50 7BEF 8C33 3B4A 4404 99DE B3B4 1583 4AEF

-----BEGIN PGP PUBLIC KEY BLOCK-----

mDMEZfl8VRYJKwYBBAHaRw8BAQdAnILhqWG/0UsMQHdA9Ju3OAj11Fh95p62yShr
vWuJYe60IVRpYW5oYW8gV2FuZyA8c2hyaWszQG1haWxib3gub3JnPoiTBBMWCgA7
FiEEIg9qUHvvjDM7SkQEmd6ztBWDSu8FAmX6FR8CGwMFCwkIBwICIgIGFQoJCAsC
BBYCAwECHgcCF4AACgkQmd6ztBWDSu+mwQD+MZZMGgppmFn4C3FGubOgBZzo1WPN
HI8FNRgCLiZbfLcA/RiogqqhyjqBDfqmhcMs3uSzweb1Iwag0ZMn2Lcb5tIJtBpz
aHJpazMgPHNocmlrM0ByaXNldXAubmV0PoiTBBMWCgA7FiEEIg9qUHvvjDM7SkQE
md6ztBWDSu8FAmX5fFUCGwMFCwkIBwICIgIGFQoJCAsCBBYCAwECHgcCF4AACgkQ
md6ztBWDSu8CXwD7BWsUmr9ROHYH2xnZEZWXDip+jE9VX3HrabaOb1bVLHAA+wYr
ZVzkMe8elZDuYESZ3zl/ijvfyOPUJl/igNMniMsOtDJUaWFuaGFvIFdhbmcgPHRp
YW5oYW8ud2FuZzJAbWFpbGJveC50dS1kcmVzZGVuLmRlPoiTBBMWCgA7FiEEIg9q
UHvvjDM7SkQEmd6ztBWDSu8FAmYdoYoCGwMFCwkIBwICIgIGFQoJCAsCBBYCAwEC
HgcCF4AACgkQmd6ztBWDSu8nDAEAuSYZ9dV5Hg1PAR+Kdhov3gHfMcH9YN1N+2/B
5y95GxoA/0F9peHOxwgWDZOjn+4Fx2Q5Fzd2KIGN2Hnupx7KOKIKuDgEZfl8VRIK
KwYBBAGXVQEFAQEHQFOYIJOL/o+39pWtTV1E3KFhEf45l1v5exTEHEPMI8gXAwEI
B4h4BBgWCgAgFiEEIg9qUHvvjDM7SkQEmd6ztBWDSu8FAmX5fFUCGwwACgkQmd6z
tBWDSu9GvgD+KEMAx7t2QnD7/KzcQjYiruZfdaJYMSMelbRxHhIYk+QA/2zRJ4O5
Deep7VLUCxv9RyrEPlQ2DJ5w4zYTcq6T6v0BuDMEZfl80xYJKwYBBAHaRw8BAQdA
qhWgPxMFinDAz0ZhdSQxPsA7aTo2URWgsYCdTiOqK1GI7wQYFgoAIBYhBCIPalB7
74wzO0pEBJnes7QVg0rvBQJl+XzTAhsCAIEJEJnes7QVg0rvdiAEGRYKAB0WIQS8
17c7wjSsudzhqUbMzAiYQf6a0AUCZfl80wAKCRDMzAiYQf6a0ADZAP9uT1yK7yNQ
400Jt7TsN2sTk1k2RdPDMKjBe35u9KE0rQEAiJSbo+43jX8wclaIS5Z1fHGHYUFN
TGA3izr3D/wvOQhm+gD/Yi9S58ktw3jKFtnnsQ5ZrlEhvT50FnbvH6Pkbn6ch8UA
/iiyxSUxlMagln0358OjdWXDq9XDA9MS3TKx/+kZpncJ
=vSKQ
-----END PGP PUBLIC KEY BLOCK-----


----------------------

retired key
DA29 39BC 46EF 7A36 FA08 B89F BBEE C439 23F0 E695

Don't use a public keyserver (ubuntu, openpgp, mit etc.)
if you find my key there it's likely outdated.

----------------------
encrypt with age, if you prefer

age10uqv0kklww2r8szfahansgejz5t5330v0u4aj0mupll3net723xqa6dnec

$ echo "hello" | age -r &LTthat-pubkey> -a encrypted.ascii

----------------------

rules of thumb

access via secure network connection (TLS) only!
don’t trust a keyid unless it’s vouched (signed) by your web-of-trust.
don’t trust a cert only because it’s found on a well-known keyserver. OpenPGP says: “whoever uploaded this cert has access to that email address (in the keyid)”.
similarly, the cert you got from here says: whoever uploaded this cert has write access to this server.
think for yourself to what extent you trust a thing

----------------------

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
My music projects - overview and listens

Related posts

中文版/CN VER

§§ die Todgeweihten - EBM/Industrial/Dark-Electro/Synthwave

Ave, Caesar, morituri te salutant!

iframe (bandcamp.com)

Bandcamp Link

Discography:

die Todgeweihten (demos 2020)
Synthesized Joy (Full album, released on bandcamp)
Isomorph (Full album, disk/digital release on bandcamp, production by Dying Art.)

also appeared on Russian Dark Community’s Dark Virus X-MAS

----------------------

§§ Normandy 2183 - Synthwave, Industrial, Synthpop

iframe (bandcamp.com)

Bandcamp Link

This is my Synthwave project. The name is a tribute to the Mass Effect.

Discography

Normandy 2183 Demos (Released on BC)
A Neon Dream (not released yet, Coming out in 2021)

----------------------

§§ Vom Verborgenen - Black Metal/Melodic Death/Post Black

iframe (bandcamp.com)

Bandcamp Link

Discography:

Unholy Incarnation (EP album, 3 off vocal demos)
Vom verborgenen (EP album, 3 songs + 1 bonus, released on bandcamp)
the stars were going out (EP album, released on bandcamp)

----------------------

§§ Return 0; - Melodic Death/Metalcore

This is my college band. Return 0; is no longer since our graduation. An album of two songs is available on xiami.com

----------------------

§§ Experimental stuff.. Various Genres.

I also make post rock and even funky stuff. Though I don’t have a seperate title for them. All above can be found on Xiami.com under the name of SHRIK3

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
My music projects - overview (chinese)

英文版/EN_VER

Note: 虾米倒下了,以后有时间再慢慢转移国内平台

§§ die Todgeweihten - EBM/电子工业/黑电/合成器浪潮

Bandcamp Link aka.SHRIK3

Discography:

die Todgeweihten (demos 2020)
Synthesized Joy (全长)
Isomorph (全长, 数字+实体)
参与Dark Virus X-MAS

Dying Art 厂牌专访

§§ Vom Verborgenen - 黑金属/后黑/旋律死亡金属/回潮敲击

Bandcamp Link

Discography:

Unholy Incarnation (EP, 三首无人声demo)
Vom verborgenen (专辑,三首 + 1 CD Bonus)
the stars were going out (单曲EP)
where is my silence (单曲EP)

§§ Normandy 2183 - 合成器浪潮/outrun

Bandcamp Link

Discography

Normandy 2183 Demos (Released on BC)
A Neon Dream (not released yet, Coming out in 2021)

§§ Return 0; - 旋律死亡金属

Return 0; 是我的大学校园乐队。自毕业以后该乐队已经解散。 两首原创可以在虾米听到。 xiami.com

§§ 实验音乐

偶尔也会做些乱七八糟的东西,funky,blues,后摇和各种翻奏改编等等,在虾米可以听到。

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
mount commands

Quick Notes on Several common mount commands
mount -t tmpfs tmpfs /mnt/ram -o size=1000M

Mount a ntfs disk:
mount -t ntfs /dev/SDX /path/to/mount_point

(ntfs-3g may be needed to support ntfs)

mout EXFAT disk:
mount -t exfat /dev/SDX /path/to/mount_point

mount a shared disk from network
sudo mount -t cifs //$HOST/public /mnt/share -o username=$USER,password=$password


via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
device number 2

This post is about handling device numbers in kernel Programming.

ref: Linux Device Drivers

§ data type:

The dev_t type defined in &LTlinux/types.h> holds a device’s number.

Use the macros in &LTlinux/kdev_t.h> to obtain the major or minor parts of dev_t:

1
2


MAJOR(dev_t dev);
MINOR(dev_t dev);

or turn a pair of major & minor numbers into dev_t:
MKDEV(int major, int minor);


§ Allocationg & Freeing Device Numbers

1
2
3
4
5


int register_chardev_region(dev_t first, unsigned int count, char *name);

int alloc_chardev_region(dev_t *dev, unsigned int firstminor, unsigned int count, char *name);

void unregister_chardev_region(dev_t first, unsigned int count);

register_chardev_region() does what its name suggests. It request access to a range of device numbers. first is the beginning device number, count is the total number of contiguous device numbers to be requested. name is the name of device; it will appear in /proc/devices and sysfs.

However it’s often unkown in advance which device number will be used. The device number can by dynamicaly allocated by the kernel on the fly with the second function alloc_chardev_region(). firstminor should be the requested first minor number to use(usually 0). The disadvantage of this method is that a node can’t be created in advance.

To load a driver using dynamic major number, a script can be called: after calling insmod, read /proc/devices to create the nodes.

These 2 functions return 0 upon success, and negative error code upon failures, in which case the requested region can’t be accessed.

The 3rd function frees the device number. It’s usually paced in module’s cleanup function.

Some major numbers are stratically assigned to the most common devices. Here is a list: Linux Kernel Documentations

So dynamic allocation is suggested…

The script to load a module (as showcased in LDD the book):
#!/bin/sh
module="name_of_module"
device="name_of_device"
mode="664"

# invoke insmod with all arguments we got
# and use a pathname, as newer modutils don't look in . by defult.
/sbin/insmod ./$module.ko $* || exit 1

# remove stale nodes
rm -f /dev/${device}[0-3]

major=$(awk "\\$2==\"$module\" {print \\$1}" /proc/devices)

mknod /dev/${device}0 c $major 0
mknod /dev/${device}1 c $major 1
mknod /dev/${device}2 c $major 2
mknod /dev/${device}3 c $major 3

# give appropriate group/permissions, and change the group.
# since this script is run by superuser, the newly created
# nodes are owned by root.
# Not all distributions have staff, some have "wheel" instead.

group="staff"
grep -q '^wheel:' /etc/group || group="wheel"

chgrp $group /dev/${device}[0-3]
chmod $mode /dev/${device}[0-3]


via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
device number 1

Some notes on linux device files.

REF:
Linux Device Drivers
This is article by Jyoti Singh
This is (part of) the result of ls -l on a normal directory.
drwxr-xr-x  2 shrik3 shrik3    4096 Jul 12 18:59 Desktop
drwx------ 3 shrik3 shrik3 4096 Jul 8 14:44 Downloads
drwxr-xr-x 8 shrik3 shrik3 4096 Jun 28 09:59 docs
-rw-r--r-- 1 shrik3 shrik3 2821 Jun 30 21:11 notes
drwxr-xr-x 4 shrik3 shrik3 4096 Jul 2 23:30 scripts
drwxr-xr-x 16 shrik3 shrik3 4096 Jul 2 23:24 temp
drwxr-xr-x 7 shrik3 shrik3 4096 Jul 2 18:19 utils

This is (part of) the result of ls -l /dev
crw-------  1 root   root      108,   0 Jul 12 16:08 ppp
crw------- 1 root root 10, 1 Jul 12 16:08 psaux
crw-rw-rw- 1 root tty 5, 2 Jul 12 20:16 ptmx
crw-rw-rw- 1 root root 1, 8 Jul 12 16:08 random
crw-rw-r-- 1 root rfkill 10, 242 Jul 12 16:08 rfkill
lrwxrwxrwx 1 root root 4 Jul 12 16:08 rtc -> rtc0
crw------- 1 root root 249, 0 Jul 12 16:08 rtc0
brw-rw---- 1 root disk 8, 0 Jul 12 16:08 sda
brw-rw---- 1 root disk 8, 1 Jul 12 16:08 sda1
brw-rw---- 1 root disk 8, 10 Jul 12 16:08 sda10
brw-rw---- 1 root disk 8, 2 Jul 12 16:08 sda2
brw-rw---- 1 root disk 8, 3 Jul 12 16:08 sda3
brw-rw---- 1 root disk 8, 4 Jul 12 16:08 sda4
brw-rw---- 1 root disk 8, 5 Jul 12 16:08 sda5
brw-rw---- 1 root disk 8, 6 Jul 12 16:08 sda6
brw-rw---- 1 root disk 8, 7 Jul 12 16:08 sda7
brw-rw---- 1 root disk 8, 8 Jul 12 16:08 sda8
crw--w---- 1 root tty 4, 2 Jul 12 16:08 tty2
crw--w---- 1 root tty 4, 20 Jul 12 16:08 tty20
crw--w---- 1 root tty 4, 21 Jul 12 16:08 tty21
crw--w---- 1 root tty 4, 57 Jul 12 16:08 tty57
crw--w---- 1 root tty 4, 8 Jul 12 16:08 tty8
crw--w---- 1 root tty 4, 9 Jul 12 16:08 tty9

The first character of each line flags the device type, they are:

For Char and Block devices, in the 5th column, there are 2 numbers separated by a comma. They are called Major and minor numbers of the device, which “replace” the SIZE column for regular nodes.

§ WHAT IS MAJOR & MINOR NUMBERS:

Traditionally, the major number identifies the driver associated with the device. For example, /dev/null and /dev/zero are both managed by driver 1, whereas virtual consoles and serial terminals are managerd by driver 4; similarly, both vcs1 and vcsa1 devides are managed by driver 7. Modern Linux kernels allow multiple drivers to share major numbers, but most devices that you will see are still organized on the one-major-one-driver principle.

The major number is an offset to the kernel’s drivers table.

The minor number is used by the kernel to determine exactly which device is being referred to. Well the kernel doesn’t acturlly care about the minor number. The minor number is used by the driver to identify instances of devices.

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
AWK basic usage

refs:
https://www.tutorialspoint.com/awk/awk_overview.htm)
man page of gawk


§ Overview

AWK is created by Alfred Aho, Peter Weinberger and Brian Kernghan from AT & T lab.

GAWK is the GNU distribution of AWK.

awk is a pattern scanning and processing language.

The routine of AWK:

1. AWK reads a line from input stream and stores it in memory.
2. All AWK commands are applied sequentially on the input.
3. Repeat until the file reaches end.

§ Structure:

1
2
3
4
5


BEGIN{commands}

/pattern/{commands}

END{commands}

1. The BEGIN block is excuted at start-up only once (this block is optional)
2. The second block is the body block, which is applied on each input line.
3. END Block is like BEGIN, but excuted at the end.

§ Command Line:
awk -f command.awk file.txt


§ Examples:

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
disk encryption (ext4)

This is a log on minimal setup of dm-crypt.

ref: Archwiki/dm-encrypt

§§ Setup

delete existing fs (use with caution).
wipefs -a /dev/sdx

Lock the partition with dm-crypt; see man page for options
crypt setup [Options] luksFormat /dev/sdx

Decrypt(open) the partition:
cryptsetup open /dev/sdx name

After unlocking the partition, it will be available at /dev/mapper/name

Create ext4 filesystem:
mkfs.ext4 /dev/mapper/name


§§ Mounting and Unmounting
# Mounting
cryptsetup open [device] [name]
mount -t [fstype] /dev/mapper/name /mnt/mntpoint

# Unmounting
umount /mnt/mntpoint
cryptsetup close [name]


§ A SIMPLE SCRIPT

gpgwiz (I call it gpgwiz because i store my gpg keypair on a usb stick). The script itself doesn’t necessarily have anything to do with GPG.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45


#!/bin/sh

# I WROTE ONLY FOR MY PERSONAL USE. IT WON'T WORK FOR YOU
# OUT OF THE BOX. TWEAK THE VARIABLES FOR YOURSELF.

UUID=xxxxgggg-cccc-bbbb-aaaa-ddddeeeeffff
NAME=GPGDATA
MOUNTPOINT=/mnt/GPGDATA_MNT

bold=$(tput bold)
normal=$(tput sgr0)

print_usage(){
echo "${bold}USAGE${normal}"
echo "gpgwiz open: unlock partition and mount"
echo "gpgwiz close: unmount partition and lock"
}

open_dev(){
echo "PREPARING DEVICE"
echo "MOUNTPOINT: $MOUNTPOINT"
cryptsetup open /dev/disk/by-uuid/$UUID $NAME
mkdir -p /mnt/$MOUNTPOINT
mount -t ext4 /dev/mapper/$NAME $MOUNTPOINT
echo "ceating symbolinks... TODO"
}

close_dev(){
umount $MOUNTPOINT
cryptsetup close $NAME
}

if [ -z $1 ]
then
print_usage
exit
fi

if [ $1 == 'open' ]; then
open_dev
elif [ $1 == 'close' ]; then
close_dev
else
print_usage
fi


via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
Prozess & Thread

Notizen auf Vorlesung [Betrieb System]

§§ Adressraum:

Prozess A
________
|Kern |
----------
|Stack | &LT---- Stack Pointer
|... |
|... |
| |
|--------|
|BSS |
|--------|
|DATA |
|--------|
|Text |
|--------|


§§ Stack-Segment: Kellerspeicher

Funktionsparameter und lokale Variablen
Ruecksprung Adresse

§§ Daten-Segment: globale Daten

Data: intialisierte Daten
BSS: “block started by symbol” per Konvention mit 0 intialisiert erweiterbar durch systemanruf

§§ Textsegment: Maschinencode

nur lesbar, ausfuehrbar
erste Seite frei zum erkennen nicht-intialisiert Pointer

§§ Thread-Zustände

1. aktiv: Thread wird gerade auf der CPU ausgeführt, Pro CPU ist zu jedem Zeitpunkt maximal ein Thread aktiv.
2. blockiert: Warten auf ein Ereignis (z.B. Botschaft, Freigabe eines Betriebsmittels) um weiterarbeiten zu können
3. bereit: nicht blockiert, aber momentan nicht aktiv. Die bereit-Menge enthält alle Threads, die ummitttelbar aktic werden können

_________        _______          __________
BLOCKIERT| &LT-----|Aktiv| &LT------ | Bereit |
_________| |_____| ------> |________|
| ^
|_________________________________|


§§ RANDBEDINGUNGEN:

Zu jeder Zeit ist höchstens eine Thread pro CPU aktiv
eine aktiber Thread ist zu jedem Zeitpunkt genau einer CPU zugeordnet.
nur die bereiten Threads erhalten CPU (werden aktiv)
Fairness: jeder THread erhält angemessenen Antel CPU-Zeit, kein Thread darf CPU für sich allein beanspruchen.
Wohlverhalten von Threads darf bei Implementierung von Threads keine Voraussetzung sein. z.B. while (true) {} darf nicht dazu führen, dass andere Threads nie wieder “drankommen”

§§ Kooperative vs. präemtive Umschaltung

Cooperative vs Preemtive

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
GPG Quick Notes

A cheatsheet for GPG

Generate Keypair:
gpg --full-gen-key

generate revoke certificate:
gpg --gen-revoke [USER-ID]

list keys:
gpg --list-keys

option:
--keyid-format short/long

delete key:
gpg --delete-key [USER-ID]

output key:
gpg --armor --output public-key.txt --export [USER-ID]

upload key:
gpg --send-keys [USER-ID] --keyserver hkp://sybkeys.pgp.net

fingerprint:
gpg --fingerprint [USER-ID]

import key:
gpg --import [key-file]

search on server for key:
gpg --keyserver hkp://sybkeys.pgp.net --search-keys [USER-ID]

encrypt for someone:
gpg -r some@mail.x -e file

decrypt:
gpg -d file.gpg

sign data:
gpg --sign file
gpg --clearsign file
gpg --detach-sign file
gpg --armor --detach-sign file

verify sig:
gpg --verify [signature file] [file]

encrypt and sign:
gpg --local-user [sender id] --recipient [receiver id] --armor --sign --encrypt file

add additional email address:
gpg --edit-key [kei/user-id]
adduid (and follow instructions)
trust (optional)

private key export and import:
gpg --export-secret-keys --armor &LTUSER-ID> privkey.asc
gpg --import privkey.asc

export subkeys:
gpg --list-secret-keys --with-subkey-fingerprint
gpg -a --export-secret-subkeys [subkey_id]! > /tmp/subkey.gpg

edit key:
gpg --edit-key &LTuser-id>

passwd #change passphrase
clean #compact any user id that is no longer usable (revoked or expired)
revkey #revoke a key
addkey #add a subkey
expire #change expiration time
addduid # add additional names
addphoto # add photo to key
save # save change and quit


via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
Vektorraum, Untervektorraum und Spannraum

Notizen - Lineare ALgebra
Vorlesung von Prof.Dr.Ulrike Baumann
---INCLUDES FORMULARS, PLS GO TO FULL TEXT FOR BETTER RENDERING---

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
关于IEEE754 单精度浮点数的定义,转换与数值范围
---INCLUDES FORMULARS, PLS GO TO FULL TEXT FOR BETTER RENDERING---

via home - SHRIK3 on SHRIK3 (author: i@shrik3.com (SHRIK3))
快速幂模的两种实现

虽然这个算法已经滥大街了,但我们离散数学课里讲的al-kachi算法与常见的二进制幂略有不同, 所以写篇笔记记录一下。伪代码通俗易懂,但具体实现比较让人不爽。

这里把两种算法的代码都写出来,另外附加一个脑袋被驴踢了的SB代码。

§§ ALGORITHM 1.

常见的快速幂模求解形如 Result = a^e mod b, 将e转化为2进制,然后按二进制位从右到左:
INPUT: a, e, b;
INIT: Res = 1, a = a mod b

LOOP (e IS NOT 0):
IF e % 2 == 1:
Res = (Res * a) mod b
END IF

a = a * a
e = e / 2
ENDLOOP

OUTPUT: Res = a^e mod b


§§ ALGORITHM 2.

我们老师说这叫Al-Kachi算法,同样将e转化为2进制,但按二进制位从左到右.
INPUT: a, e, b;
INIT: Res = 1, a = a mod b

LOOP (digit d in binary e, from left to right):
IF d == 1:
Res = Res * Res * a mod b
ELSE:
Res = Res * Res mod b
ENDIF
ENDLOOP

OUTPUT: Res = a^e mod b


§§ CODE:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78