-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGetFixBytes.ps1
52 lines (50 loc) · 1.67 KB
/
GetFixBytes.ps1
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
function GetFixBytes([string]$text, [int]$count, [System.Text.Encoding]$enc_dst, [string]$padding_str = " ") {
[int]$cnt = 0
[byte[]]$dst_bytes = @()
Foreach ($ch in [System.Globalization.StringInfo]::GetTextElementEnumerator($text)) {
$b = $enc_dst.GetBytes($ch)
if ($cnt + $b.Length -gt $count) {
break
}
$dst_bytes += $b
$cnt += $b.Length
}
[int]$r = $count - $cnt
if ($r -gt 0) {
$b = $enc_dst.GetBytes($padding_str)
$dst_bytes += $b * [Math]::Truncate($r / $b.Length)
[int]$rem = $r % $b.Length
if ($rem -gt 0) {
$dst_bytes += [byte[]]@(0) * $rem
}
}
return $dst_bytes
}
# Sample 1
$enc_dst = [System.Text.Encoding]::GetEncoding('UTF-16')
$dst_bytes = GetFixBytes "test𠀋日本語" 11 $enc_dst "*"
[System.IO.File]::WriteAllBytes(".\write.txt", $dst_bytes)
# Sample 2
$csvall = Import-Csv -Path "sample.csv"
$enc_dst = [System.Text.Encoding]::GetEncoding('UTF-16')
[void](New-Item -ItemType file utf16.csv -Force)
Foreach ($csv in $csvall) {
[byte[]]$dst_bytes = @()
$dst_bytes += GetFixBytes $csv.ID 12 $enc_dst
$dst_bytes += GetFixBytes $csv.Date 12 $enc_dst
$dst_bytes += GetFixBytes $csv.Note 20 $enc_dst
$dst_bytes += GetFixBytes "`r`n" 4 $enc_dst
$dst_bytes | Add-Content "utf16.csv" -Encoding Byte
}
# Sample 3
$csvall = Import-Csv -Path "sample.csv"
$enc_dst = [System.Text.Encoding]::GetEncoding('shift_jis')
[void](New-Item -ItemType file sjis.csv -Force)
Foreach ($csv in $csvall) {
[byte[]]$dst_bytes = @()
$dst_bytes += GetFixBytes $csv.ID 10 $enc_dst
$dst_bytes += GetFixBytes $csv.Date 10 $enc_dst
$dst_bytes += GetFixBytes $csv.Note 10 $enc_dst
$dst_bytes += GetFixBytes "`r`n" 2 $enc_dst
$dst_bytes | Add-Content "sjis.csv" -Encoding Byte
}