将十六进制转换为扩展的ASCII 0-255,没有 UTF 用于 DOS C#

如何解决将十六进制转换为扩展的ASCII 0-255,没有 UTF 用于 DOS C#

首先,当我问这么长的问题时,我不想成为“那个家伙”,尽管我知道有人以不同的方式问过很多次,但我在获取日期格式方面遇到了重大问题正确存储在字符串中。

一些小背景。

我使用的 DOS FileTime 日期格式需要以 8 个字符的十六进制格式存储 - 如下所示:https://doubleblak.com/blogPosts.php?id=7

简而言之,就是捕获时间和日期,然后以二进制位排列,然后转换为HEX。

我现在需要做的是,将这些 HEX 值存储为字符串,并能够将它们传递给 tagLib sharp 以在 MP3 文件中写入自定义 APE 标签。说起来容易做起来难...

编写自定义标签很容易,因为基本上就是这样:

TagLib.File file = TagLib.File.Create(filename);
TagLib.Ape.Tag ape_tag = (TagLib.Ape.Tag)file.GetTag(TagLib.TagTypes.Ape,true);

// Write - for my example
/* declarations: 
    public void SetValue(string key,string value);
    public void SetValue(string key,uint number,uint count);
    public void SetValue(string key,string[] value);
*/
ape_tag.SetValue("XLastPlayed",history );

那么,进入实际问题:

将日期转换为正确的十六进制值后,我得到以下结果:

928C9D51

但是,为了使这项工作正常进行并正确存储,我需要将其转换为 ASCII 值,以便 TagLibSharp 可以存储它。

如果我将其转换为 ASCII,则会得到以下结果:(这是错误的),因为它应该只有 4 个 ASCII 字符长 - 即使它们不可打印,或者位于 > 127 个字符范围内。

"\u0092\u008c\u009dQ"

您可以在此图像中看到已存储的额外 HEX 值,这是不正确的。

enter image description here

这是我一直在尝试使用的代码示例(以各种形式)以使其工作。

string FirstHistory = "7D8C9D51";
 
String test1 = "";

for (int i = 0; i < FirstHistory.Length; i += 2)
{
    string hs = FirstHistory.Substring(i,2);
     
    var enc = Encoding.GetEncoding("iso-8859-1"); //.ASCII;// .GetEncoding(437); 
    var bytes1 = enc.GetBytes(string.Format("{0:x1}",Convert.ToChar(Convert.ToUInt16(hs,16)))); 
    string unicodeString = enc.GetString(bytes1); 
    Console.WriteLine(unicodeString);  
    test1 = test1 + unicodeString;
}

// needs to be "00 00 00 21" for the standard date array for this file format.
byte[] bytesArray = { 0,33 }; // A byte array containing non-printable characters
     
string s1 = "";  
string history = ""; 

// Basically what the history will look like
// "???!???!???!???!???!???!???!???!???!???!???!???!???!???!???!???!???!"

for (int i =0; i < 18; i++)
{            
    if(i==0) {
        history = test1; // Write the first value.
    } 

    s1 = Encoding.UTF8.GetString(bytesArray); // encoding on this string won't effect the array date values
    history = history + s1;     
}

ape_tag.SetValue("XLastPlayed",history );

我知道有多种编码,我基本上已经尝试了所有我能做的,并且阅读了一些东西,但我什么也没有得到。

有时我想我已经知道了,但是当我查看我正在保存的文件时,它会滑入一个“C2”十六进制值,而它不应该,这是破坏一切的 unicode。我已经包含了一张图片,说明没有这些 C2 十六进制值应该是什么,您实际上可以看到 DOS 时间和日期时间在 HxD 十六进制查看器中正确显示。

enter image description here

我尝试了各种编码,例如 437、ios-8859-1、ASCII,以及不同的方法,例如使用字符串生成器、字符、字节等,有时我会得到一个日期和时间戳,其中的值是正确的,其中 HEX 值不超过扩展的 ASCII 范围,但随后我再次运行它,然后返回到第 1 方格。它总是将这些扩展值作为 UTF8 条目插入并中断,无论我做什么。

我确定 VS 中没有错误,但我正在运行 Microsoft Visual Studio Community 2019,版本 16.8.2,如果这增加了这种情况。

我似乎无法解决这个问题。有没有人对此有任何想法?

提前致谢。

*** 更新 ***

此更新感谢@xanatos

public static byte[] ConvertHexStringToByteArray(string str)
{
    Dictionary<string,byte> hexindex = new Dictionary<string,byte>();
    for (int i = 0; i <= 255; i++)
        hexindex.Add(i.ToString("X2"),(byte)i);
    List<byte> hexres = new List<byte>();
    for (int i = 0; i < str.Length; i += 2)
        hexres.Add(hexindex[str.Substring(i,2)]);
    return hexres.ToArray();
}

string FirstHistory = "7D8C9D51";
 
string s1 = "";  
string history = ""; 
byte[] bytes = { 0,33,0 }; // A byte array contains non-ASCII (or non-readable) characters
for (int i =0; i < 18; i++)
{   
    s1 = Encoding.UTF8.GetString(bytes); // ???
    history = history + s1;
}

var theArray_SO = ConvertHexStringToByteArray(FirstHistory);
ape_tag.SetItem(new TagLib.Ape.Item("XLastPlayed",(new TagLib.ByteVector(theArray_SO)) + history));  

*** 更新 2 - 2021 年 1 月 30 日 ***

在编辑其他值并重新保存后,我遇到了一些麻烦。似乎 TagLib 和自定义 APE 标签可能存在数据损坏,特别是对于这个 ByteVector 数据。如果您只是使用 save 方法来编辑其他自定义值,那么这不是问题,但是如果您的自定义值包含这些值和 ByteVector 值,您很可能会遇到麻烦。这是我保存文件时仍然使用的。

TagLib.File file = TagLib.File.Create(filename);
// changes
file.save();

但是,为了克服这种数据损坏,我首先将文件作为 FileStream 读取(搜索)以定位我需要的值,然后将找到的值后 72 个字节的值放入一个新的字节数组中,然后将其保存返回文件。

我发现通过字符串读取 ByteVector 数据非常失败,结果到处都是。

TagLib.Ape.Item item_Duration = ape_tag.GetItem("XLastScheduled");

虽然这可能可以用一千种方式重写,但这是我的代码。

int foundlocation = 0;
int loop1 = 0;                
byte[] sevenItems = new byte[80] { 0,0 };
string match = "XLastScheduled";
byte[] matchBytes = Encoding.ASCII.GetBytes(match);
{
    using (var fs = new FileStream(filename,FileMode.Open))
    {
        int i = 0;
        int readByte;
        while ((readByte = fs.ReadByte()) != -1)
        {

            if (foundlocation == 0)
            {
                if (matchBytes[i] == readByte)
                {
                    i++;
                }
                else
                {
                    i = 0;
                }
            }

            if (i == matchBytes.Length)
            {
                //Console.WriteLine("It found between {0} and {1}.",fs.Position - matchBytes.Length,fs.Position);
                // set to true.
                foundlocation = 1;
            }

            if (foundlocation==1)
            {
                //if (loop1 > 1)
                {
                    // Start adding it at 2 bytes after it's found.
                    sevenItems[loop1] = (byte)readByte;
                }

                loop1++;

                if(loop1 > 79) 
                {

                    fs.Close();
                    Console.WriteLine("Found the XLastScheduled data");
                    // 72/4 = 18 date/times
                    break;
                }
            }
            // Then,I can save those values back as a vector byte array,instead of a string - hopefully...

        }
        fs.Close();
    }
}

byte[] dst = new byte[sevenItems.Length - 8];
Array.Copy(sevenItems,2,dst,dst.Length);
 




TagLib.File file = TagLib.File.Create(filename); 
// Get the APEv2 tag if it exists.
TagLib.Ape.Tag ape_tag = (TagLib.Ape.Tag)file.GetTag(TagLib.TagTypes.Ape,true);




// Save the new byteVector.
ape_tag.SetItem(new TagLib.Ape.Item("XLastScheduled",(new TagLib.ByteVector(dst))));
Console.WriteLine("XLastScheduled: set"  );

解决方法

还有另一种二进制数据的方法:

var bytes = new byte[4] { 0xFF,0xFF };
ape_tag.SetItem(new TagLib.Ape.Item("XLastPlayed",new ByteVector(bytes)));

不清楚您是否需要从/向 DOS FileTime 转换的方法:

public static uint ToDosFileTimeDate(DateTime dt)
{
    ushort date = (ushort)(((dt.Year - 1980) << 9) | (dt.Month << 5) | (dt.Day));
    ushort time = (ushort)((dt.Hour << 11) | (dt.Minute << 5) | (dt.Second >> 1));

    uint dateTime = ((uint)date << 16) | time;
    return dateTime;
}

public static DateTime FromDosFileTimeDate(uint ui)
{
    ushort date = (ushort)(ui >> 16);
    ushort time = (ushort)(ui & 0xFFFF);

    var year = (date >> 9) + 1980;
    var month = (date >> 5) & 0xF;
    var day = date & 0x1F;

    var hour = time >> 11;
    var minute = (time >> 5) & 0x3F;
    var second = (time & 0x1F) << 1;

    return new DateTime(year,month,day,hour,minute,second,DateTimeKind.Local);
}

并将 uint 转换为 byte[4] 数组有

uint ui = BitConverter.ToUInt32(bytes);

byte[] bytes = BitConverter.GetBytes(ui);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-